Comparator - int cannot be dereferenced

后端 未结 3 1439
滥情空心
滥情空心 2021-01-25 14:24

So I saw an example on here how to sort an ArrayList using the Comparator interface, so I tried it out. With Strings it worked perfectly, but with one variable that I want to so

相关标签:
3条回答
  • 2021-01-25 14:27

    Fyi, although this doesn't answer your specific question about the int dereferencing error, in Java 8 you don't need the dedicated comparator class at all. You can simply write:

    yourList.sort((r1, r2) -> Integer.compare(r1.getScore(), r2.getScore()));
    

    or

    yourList.sort(Comparator.comparingInt(Review::getScore));
    

    both of which are much nicer ways to do it.

    0 讨论(0)
  • 2021-01-25 14:44

    try this:

    public class ScoreComparator implements Comparator<Review> {
    
        @Override
        public int compare(Review o1, Review o2)
        {
             return (o1.getScore()<o2.getScore() ? -1 : (o1.getScore()==o2.getScore() ? 0 : 1));
        }
    }
    
    0 讨论(0)
  • 2021-01-25 14:51

    You can't call methods on ints; there's no compareTo method to call. That would be on the boxed Integer type, but boxing would be overkill.

    If you're on Java 7+, you should write

    return Integer.compare(o1.getScore(), o2.getScore());
    

    ...otherwise you'll more or less need to write

    if (o1.getScore() < o2.getScore()) {
       return -1;
    } else if (o1.getScore() > o2.getScore()) {
       return 1;
    } else {
       return 0;
    }
    
    0 讨论(0)
提交回复
热议问题