Sorting an ArrayList of objects using a custom sorting order

后端 未结 11 1521
说谎
说谎 2020-11-22 00:14

I am looking to implement a sort feature for my address book application.

I want to sort an ArrayList contactArray. Contact

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 00:37

    use this method:

    private ArrayList sortList(ArrayList list) {
        if (list != null && list.size() > 1) {
            Collections.sort(list, new Comparator() {
                public int compare(myClass o1, myClass o2) {
                    if (o1.getsortnumber() == o2.getsortnumber()) return 0;
                    return o1.getsortnumber() < o2.getsortnumber() ? 1 : -1;
                }
            });
        }
        return list;
    }
    

    `

    and use: mySortedlist = sortList(myList); No need to implement comparator in your class. If you want inverse order swap 1 and -1

提交回复
热议问题