Collections sort not being accepted by Eclipse

后端 未结 5 1642
梦如初夏
梦如初夏 2021-01-19 06:58
    import java.io.BufferedReader;
    import java.util.Collections;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader         


        
5条回答
  •  既然无缘
    2021-01-19 07:12

    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
    { 
        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
    {
        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 list = new ArrayList();
            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 inputData(Scanner in)
        {
            ArrayList list = new ArrayList();
            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.

提交回复
热议问题