Implements Comparable to get alphabetical sort with Strings

后端 未结 4 2257
你的背包
你的背包 2021-02-20 14:04

I would like an object to be comparable (to use it in a TreeSet in that case).

My object got a name field and I would like it to be sorted by alphabetical order.

4条回答
  •  天涯浪人
    2021-02-20 14:51

    I think you want something like this

    package mine;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    public class MyObject {
        private String name;
    
        public MyObject(String name) {
            this.name = name;
        }
    
        public MyObject() {
            // TODO Auto-generated constructor stub
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    
    
        @Override
        public String toString() {
            return "MyObject [name=" + name + "]";
        }
    
        public static void main(String[] args){
            List l = new ArrayList<>();
            l.add(new MyObject("Ab"));
            l.add(new MyObject("AA"));
            l.add(new MyObject());
    
            Collections.sort(l, new Comparator(){
    
                @Override
                public int compare(MyObject o1, MyObject o2) {
                    if (o1.name == null && o2.name == null){
                        return 0;
                    }else if (o1.name == null){
                        return -1;
                    }else if (o2.name == null){ 
                        return 1;
                    }else{
                        return o1.name.toUpperCase().compareTo(o2.name.toUpperCase());
                    }
                }
    
            });
    
            System.out.println(l);
        }
    }
    

提交回复
热议问题