Android java custom sorting using Comparable

后端 未结 3 1141
-上瘾入骨i
-上瘾入骨i 2021-01-20 11:11
  @Override
      public int compareTo(final myRow another) {

        final int BEFORE    =-1;
        final int EQUAL     = 0;
        final int AFTER     = 1;

           


        
3条回答
  •  伪装坚强ぢ
    2021-01-20 11:37

    Your code looks a bit complex. The simplest way would be to start from the highest priority field and move down to other fields. An example code would be:

    public class Member implements Comparable {
    
        static enum Status {
            NORMAL(1), FRIEND(2), BANNED(3);
    
            private final int order;
    
            Status(int order) {
                this.order = order;
            }
    
            public int getOrder() {
                return this.order;
            }
    
        };
    
        private final String name;
    
        private final Status status;
    
        public Member(final String name, final Status status) {
            this.name = name;
            this.status = status;
        }
    
        @Override
        public int compareTo(Member o) {
            if (this.status.equals(o.status)) {
                return this.name.compareTo(o.name);
            } else {
                return this.status.compareTo(o.status);
            }
        }
    
        @Override
        public String toString() {
            return "Member [name=" + name + ", status=" + status + "]";
        }
    
        public static void main(String[] args) throws Throwable {
            Member[] members = {
                            new Member("abrt", Status.FRIEND),
                            new Member("dfgh", Status.FRIEND),
                            new Member("abdf", Status.NORMAL),
                            new Member("wert", Status.NORMAL),
                            new Member("andgh", Status.BANNED),
                            new Member("qwer", Status.BANNED)
            };
            List lst = Arrays.asList(members);
            Collections.sort(lst);
            System.out.println(lst);
        }
    
    
    }
    

提交回复
热议问题