关于 java:Collections sort 不被 Eclipse 接受

Collections sort not being accepted by Eclipse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    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 不喜欢后面的 add 语句,也就是说: ArrayList(SortNames.CelebrityNamesFile) 类型中的方法 add (SortNames.CelebrityNamesFile) 不适用于参数 (String)

1
2
3
4
5
6
                 else
                 {
                     myCelebrityList.add( oneName );
                 }
            }
            celebrityNamesFile.close();

$
然后它不喜欢我的排序声明,即:
绑定不匹配:集合类型的泛型方法 sort(List T) 不适用于参数 (ArrayList (SortNames.CelebrityNamesFile))。推断类型 SortNames.CelebrityNamesFile 不是有界参数的有效替代品 (T extends Comparable(? super T))

1
2
3
4
5
6
7
            Collections.sort( myCelebrityList );
            System.out.println( myCelebrityList );

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

}

我做错了什么?我在这里阅读了很多帖子,阅读了关于比较器的 Java 文档,阅读了关于比较器的 Java 教程。 Head First Java,Ivor Horton 的 Java 7 开始。仍然一无所知。

该程序的目的是从txt文件中读取名称,将它们添加到一个数组列表中,按自然顺序打印数组列表,按姓氏对数组列表进行排序,再次打印列表。


对于第一个问题,问题相当简单。 oneName 是一个 String,而 myCelebrityListCelebrityNamesFile 的集合 - 这意味着您只能将对象添加到 CelebrityNamesFile.

类型的集合中

对于第二个问题,您的问题是 CelebrityNamesFile 类没有实现 Comparable 接口。排序要求为列表元素类型实现排序,例如通过为类实现 Comparable 或向 sort.

提供 Comparator


对于第一个问题,您尝试将 String 添加到 List<CelebrityNamesFile> 实例中。您应该使用 String 创建一个 CelebrityNamesFile 实例并将此实例添加到您的列表中:

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

对于第二个问题,请尝试

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

正如@alyu 所指出的,CelebrityNamesFile 类需要实现 Comparable 接口来处理您发布的代码,但您也可以添加一个 Comparator<CelebrityNamesFile> 实例(并且您已经拥有 实现它的类).

更多相关信息:

  • 收藏#sort

CompareLastName 类中实现的Comparator 可以放在SortNames 类之外,或者至少在CelebrityNamesFile 类之外。在我将实现 Comparator 的类放在对象类之外之前,我遇到了完全相同的问题。在我这样做之后,该程序运行良好。这是我的代码示例,如果有帮助,请附上注释。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// 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;
    }
}

注意:我的回答是在原始帖子发布一年后,但希望它可以帮助任何访问此站点寻求帮助的人。


集合 myCelebrityListCelebrityNamesFile 类型,这意味着它只能接受该类的实例。您需要创建一个 CelebrityNamesFile 实例并将其添加到集合中。 Collections 不会接受你的集合,因为你的类 CelebrityNamesFile 没有实现 Comparator 接口。您需要将比较器实例作为第二个参数传递给 Collections.sort()


  • 您正在尝试将 String(对象 oneName)添加到 CelebrityNamesFile 的列表中。您需要以某种方式从这个 String 中创建一个 CelebrityNamesFile
  • Collections.sort() 仅适用于 Comparable 的对象,前提是您未明确传递比较器。试试这个:

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