Sort an ArrayList by primitive boolean type

2019-01-18 20:44发布

I want to sort my ArrayList using a boolean type. Basically i want to show entries with true first. Here is my code below:

Abc.java

public class Abc {
 int id;
 bool isClickable;

 Abc(int i, boolean isCl){
    this.id = i;
    this.isClickable = iCl;
 }
 }

Main.java

List<Abc> abc = new ArrayList<Abc>();

//add entries here

//now sort them
Collections.sort(abc, new Comparator<Abc>(){
        @Override
        public int compare(Abc abc1, Abc abc2){

            boolean b1 = abc1.isClickable;
            boolean b2 = abc2.isClickable;

            if (b1 == !b2){
                return 1;
            }
            if (!b1 == b2){
                return -1;
            }
            return 0;
        }
    });

Order before sorting: true true true false false false false true false false

Order after sorting: false false true true true true false false false false

7条回答
一纸荒年 Trace。
2楼-- · 2019-01-18 21:02

A simple suggestion would be to use the object Boolean instead of boolean and use Collections.sort.

However, you must know that the false will be before the true because true are represented as 1 and false as 0. But then, you could just change your algorithm and access in reverse order.

Edit : As soulscheck stated, you could use Collections.reverseOrder to revert the ordering imposed by the Comparator.

查看更多
登录 后发表回答