简体   繁体   English

排序arraylist。 整数值比较

[英]Sorting arraylist. Comparation by int value

I'd like to sort my Listview by int value. 我想按int值对Listview进行排序。 I've looked in similar questions and solutions and have done something like this but it is not sorting listView descending (nothing happens btw). 我看过类似的问题和解决方案,并做了类似的事情,但它不是对listView降序排序(顺便说一句什么也没有发生)。 In arrayList are objects which this object has field named "rating". arrayList中的对象是该对象具有名为“ rating”的字段。 Here is a code: 这是一个代码:

public class GifModel implements Comparable<GifModel>, Comparator<Integer>{
.......
.......

@Override
    public int compare(Integer lhs, Integer rhs) {
        // TODO Auto-generated method stub
        return lhs.intValue() > rhs.intValue() ? 1:0;
    }

}

And in main activity. 并且在主要活动中。 "ratingSort" is a List: “ ratingSort”是一个列表:

ratingSort = new ArrayList<GifModel>(list);

    Collections.sort(ratingSort, new Comparator<GifModel>() {
        @Override
        public int compare(GifModel lhs, GifModel rhs) {
        return lhs.compare(lhs.getRating(),rhs.getRating());
        }

        });

Change your sorting comparator to this and you should be good to go: 将排序比较器更改为此,您应该可以进行以下操作:

Collections.sort(ratingSort, new Comparator<GifModel>() {

    @Override
    public int compare(GifModel lhs, GifModel rhs) {
        if (lhs.getRating() < rhs.getRating())
            return -1;
        else if (lhs.getRating() > rhs.getRating())
            return 1;
        return 0;
    }

});

You don't want to sort the listview, but the collection which you are adapting to it. 您不想对列表视图进行排序,而是要对列表视图进行排序。 You can do a simple Comparator() to accomplish so. 您可以执行一个简单的Comparator()来实现。

For your requirement, it is redundant to make your GifModel impl. 根据您的要求,将GifModel实现为多余的。 Comparator , if it has already impl. Comparator (如果已经暗示)。 Comparable<GifModel> . Comparable<GifModel>

You can just implement the compareTo(GifModel o) method, and there compare the gifModelObj.getRating() thus you can just Collections.sort(ratingSort) 您可以只实现compareTo(GifModel o)方法,然后在那里比较gifModelObj.getRating()这样您就可以只使用Collections.sort(ratingSort)

If you had requirements like sorting the list by any possible field of GifModel , you can let your GifModel implement neither Comparator nor Comparable. 如果您有按any possible field of GifModelany possible field of GifModel列表进行排序的要求,则可以让GifModel既不实现Comparator也不实现Comparable。 And create a number of Comparators for the sorting. 并创建多个Comparators进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM