Sorting of ArrayList

后端 未结 5 2265
渐次进展
渐次进展 2020-12-10 22:24

I have one array list

ArrayList itemListWithRank = ItemListDAO.getItemList();

and in arraylist itemListWithRank there are lot

5条回答
  •  遥遥无期
    2020-12-10 22:54

    First of all, every objects in the ArrayList must have some common parent in their hierarchy or implements an interface which define some way to get the rank. For example, all of them must implement this interface :

    interface Rankable {
        public int getRank();
    }
    

    The you can create a custom Comparator :

    Comparator myComparator = new Comparator() {
        public int compare(Rankable o1, Rankable o2) {
            return o1.getRank() - o2.getRank();
        }
        public equals(Object obj) {
            return obj == this;
        }
    }
    

    And finally sort your ArrayList :

    Collections.sort(itemListWithRank, myComparator);
    

    You can also implements Comparable in all your objects in the ArrayList and then the legacy sort method, but this will be less flexible if you're planning on doing other kind of comparison on them.

提交回复
热议问题