【问题标题】:Collections sort not being accepted by EclipseEclipse 不接受集合排序
【发布时间】:2012-07-16 23:22:54
【问题描述】:
    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)

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

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

            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 文件中读取名称,将它们添加到 arraylist,按自然顺序打印 arraylist,按姓氏对 arraylist 排序,再次打印列表。

【问题讨论】:

  • 而不是写散文评论打断你的代码,你应该使用一个可以复制粘贴到IDE中的正确代码块,并用cmets指出重要的行。 (另外,删除imports,它们只会混淆代码。)如果您需要更长的散文,请参阅您之前指出的行。

标签: java sorting collections comparator


【解决方案1】:

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

// 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;
    }
}

注意:我的回答是在原帖发布一年之后,但希望它能帮助任何访问该网站寻求帮助的人。

【讨论】:

    【解决方案2】:

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

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

    第二个问题,试试

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

    正如@alyu 指出的那样,CelebrityNamesFile 类需要实现Comparable 接口才能使用您发布的代码,但您也可以添加Comparator&lt;CelebrityNamesFile&gt; 实例(并且您已经拥有CompareLastName实现它的类)。

    更多信息:

    【讨论】:

      【解决方案3】:

      对于第一个问题,问题相当简单。 oneNameStringmyCelebrityListCelebrityNamesFile 的集合——这意味着您只能将对象添加到CelebrityNamesFile 类型的集合中。

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

      【讨论】:

      • +1 好答案...对于新手 :) 欢迎来到 SO!顺便说一句,它应该实现 Comparable&lt;CelebrityNamesFile&gt; - 因为 1.5,Comparable 被键入
      • 是的,这是一种方法,但请检查 OP 是否已经实现了 Comparator。
      • 我确实注意到了,但我觉得简单地告诉某人使用函数的显式比较器版本并不能解释错误消息:)
      【解决方案4】:

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

      【讨论】:

        【解决方案5】:
        1. 您正在尝试将String(对象oneName)添加到CelebrityNamesFiles 的列表中。你需要从这个String 中创建一个CelebrityNamesFile
        2. Collections.sort() 仅适用于 Comparable 的对象,前提是您没有明确传递比较器。试试这个:

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

        【讨论】:

          猜你喜欢
          • 2016-09-07
          • 1970-01-01
          • 2017-06-06
          • 1970-01-01
          • 1970-01-01
          • 2017-08-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多