Collections sort not being accepted by Eclipse

24,039

Solution 1

For the first issue, the problem is fairly simple. oneName is a String, and myCelebrityList is a collection of CelebrityNamesFile- which means that you can only add objects to the collection of type CelebrityNamesFile.

For the second issue, your problem is that the CelebrityNamesFile class does not implement the Comparable interface. Sorting requires that an ordering is implemented for the list element type, e.g. by implementing Comparable for the class or providing a Comparator to the sort.

Solution 2

For first issue, you're trying to add a String into a List<CelebrityNamesFile> instance. You sould use the String to create a CelebrityNamesFile instance and add this instance to your list:

CelebrityNamesFile celebrityNamesFile = new CelebrityNamesFile();
celebrityNamesFile.lastName = oneName;
myCelebrityList.add( celebrityNamesFile );

For second issue, try

Collections.sort(myCelebrityList, new CompareLastName());

As @alyu points, the CelebrityNamesFile class needs to implement the Comparable interface to work with the code you're posting, but you could also add a Comparator<CelebrityNamesFile> instance (and you already have the CompareLastName class that implements it).

More about this:

Solution 3

  1. You're trying to add a String (the object oneName) to a list of CelebrityNamesFiles. You need to somehow create a CelebrityNamesFile out of this String.
  2. Collections.sort() only works on objects that are Comparable if you don't explicitly pass a comparator. Try this instead:

    Collections.sort(myCelebrityList, new CelebrityNamesFile.CompareLastName());

Solution 4

The collection myCelebrityList is of type CelebrityNamesFile and that means it can only accept instances of that class. You need to create an instance of CelebrityNamesFile and add it to the collection. The Collections wont accept your collection because you class CelebrityNamesFile does not implement the Comparator interface. You need to pass your comparator instance to the Collections.sort() as second parameter.

Solution 5

The Comparator implemented in the CompareLastName class can be put outside the SortNames class, or at least outside the CelebrityNamesFile class. I was having the exact same issue until I put the class that implements my Comparator outside of my object class. After I did this, the program worked perfectly. Here's a sample of my code with comments if it helps.

// Comparator interface for my Word Class.
public interface Comparator<Word>
{ 
    int compare(Word first, Word second); 
}

// Word Class, which is my object.
public class Word
{
    private String word;
    public Word(String input)  { word = input; }
    public String get()  { return word; }
    public int wordSize()  { return word.length(); }
}

// Comparator implementation is separate from my Word Class.
public class WordComparator implements Comparator<Word>
{
    public int compare(Word first, Word second)
    {
        if (first.wordSize() < second.wordSize())  { return -1; }
        else if (first.wordSize() > second.wordSize())  { return 1; }
        else  { return first.get().compareTo(second.get()); }
    }
}

// Now run the program to ensure the Word Class objects and the WordComparator
// Class are implemented correctly.
public class WordComparatorDemo
{
    public static void main(String[] args) throws FileNotFoundException
    {
        ArrayList<Word> list = new ArrayList<Word>();
        JFileChooser find = new JFileChooser();
        Scanner read = null;
        if(find.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        {
            File selectedFile = find.getSelectedFile();
            read = new Scanner(selectedFile);
            try
            {
                list = inputData(read);
                // Here's the sort implementing the WordComparator.
                Collections.sort(list, new WordComparator());
            }
            finally  { read.close(); }
        }
    }
    public static ArrayList<Word> inputData(Scanner in)
    {
        ArrayList<Word> list = new ArrayList<Word>();
        in.useDelimiter("[^A-Za-z]+");
        while(in.hasNext())
        {
            String word = in.next();
            Word temp = new Word(word);
            list.add(temp);
        }
        return list;
    }
}

Note: My answer is a year after the original post, but hopefully it will help anyone who visits this site for help.

Share:
24,039
Armando Moncada
Author by

Armando Moncada

Legacy programmer for many years. Switching to Java. Learning the language by reading books: Head First Java, Ivor Horton's Beginning Java 7, Just Java. Doing the lessons on the Java Ranch Cattle Drive. Incredibly handsome and intelligent.

Updated on October 26, 2020

Comments

  • Armando Moncada
    Armando Moncada over 3 years
        import java.io.BufferedReader;
        import java.util.Collections;
        import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.FileReader;
        import java.io.IOException;
        import java.util.ArrayList;
        import java.util.Comparator;
        import java.util.Date;
        import java.util.List;
        import com.javaranch.common.TextFileIn;
    
        public class SortNames 
        {
            public static class CelebrityNamesFile
            {
                public String firstName;
                public String lastName;
    
                public static class CompareLastName implements Comparator< CelebrityNamesFile >
                {
                    @Override
                    public int compare( CelebrityNamesFile o1,  CelebrityNamesFile o2 )
                    {
                        return o2.lastName.compareTo( o1.lastName );
                    }
                }
    
            public static void main( String[ ] args ) throws IOException
            {
    
                ArrayList< CelebrityNamesFile > myCelebrityList;
                myCelebrityList = new ArrayList< CelebrityNamesFile >();
    
                TextFileIn celebrityNamesFile = new TextFileIn( "celebrityNamesFile.txt" );
                boolean doneReadingCelebrityNames = false;
                while ( ! doneReadingCelebrityNames )
                {
                     String oneName = celebrityNamesFile.readLine();
                     if ( oneName == null )
                     {
                         doneReadingCelebrityNames = true;
                     }
    

    $ Eclipse doesn't like the add statement that follows, to wit: The method add (SortNames.CelebrityNamesFile) in the type ArrayList(SortNames.CelebrityNamesFile)is not applicable for the arguments (String)

                     else
                     {
                         myCelebrityList.add( oneName );
                     }
                }
                celebrityNamesFile.close();
    

    $ And then it doesn't like my sort statement, to wit: Bound mismatch: The generic method sort(List T) of type Collections is not applicable for the arguments (ArrayList (SortNames.CelebrityNamesFile)). The inferred type SortNames.CelebrityNamesFile is not a valid substitute for the bounded parameter (T extends Comparable(? super T))

                Collections.sort( myCelebrityList );
                System.out.println( myCelebrityList );
    
                Collections.sort( myCelebrityList, new CelebrityNamesFile.CompareLastName() );
                System.out.println( myCelebrityList );
    }
    }
    

    }

    What am I doing wrong? I have read many posts here, have read the Java docs regarding comparator, have read Java tutorials regarding comparator. Head First Java, Ivor Horton's beginning Java 7. Still clueless.

    The purpose of the program is to read names from a txt file, add them to an arraylist, print the arraylist in its natural order, sort the arraylist by last name, print the list again.

  • Bohemian
    Bohemian almost 12 years
    +1 Good answer... for a newbie :) Welcome to SO! btw, it should implement Comparable<CelebrityNamesFile> - since 1.5, Comparable is typed
  • Luiggi Mendoza
    Luiggi Mendoza almost 12 years
    Yes, that's one method, but check that OP has already implemented a Comparator.
  • alyu
    alyu almost 12 years
    I did notice that, but I feel that simple telling someone to use the explicit comparator version of the function doesn't explain the error message :)