public static void main(String[] args) {
        
        int[] dd = {12,34,46,123,23,2,35,13,543231,65,5645,57};
        Arrays.sort(dd);
        System.out.println(Arrays.toString(dd));  // 常用数组排序,算法是快速排序算法
        
        List<Student> ls = new ArrayList<Student>(); 
        ls.add(new Student(2, "12123"));
        ls.add(new Student(54, "12334"));
        ls.add(new Student(32, "354123"));
        ls.add(new Student(6, "12654623"));
        ls.add(new Student(7, "456423"));
    
        
        Collections.sort(ls);  // 对象集合排序,依赖对象的compare方法 优点排序方式可以复用,但是不够灵活
        for(Student st : ls){
            System.out.println(st.toString());
        }
        Collections.sort(ls ,new Comparator<Student>(){  // 对象集合排序,需要每次写比较方法

            @Override
            public int compare(Student o1, Student o2) {
                // TODO Auto-generated method stub
                if(o1.getName().compareTo(o2.getName()) == 0){
                    return o1.getName().compareTo(o2.getName());
                }else{
                    return o1.getId() - o2.getId();
                }
            }
            
        });
        System.out.println("------------------------------");
        for(Student st : ls){
            System.out.println(st.toString());
        }
    }
}


class Student implements Comparable{
    int id;
    String name ;
    
    public Student(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Object o) {
        // TODO Auto-generated method stub
        if(this.id != ((Student)o).getId()){
            return this.id - ((Student)o).getId();
        }else{
            return this.name.compareTo(((Student)o).getName());
        }
    }

    @Override
    public String toString() {
        return "id=" + id + ", name=" + name;
    }
    
}

 

posted on 2017-05-24 10:48  秦水坡  阅读(234)  评论(0编辑  收藏  举报