工具类Collections的三个常用方法
/*集合工具类Collections
* 1.addAll(集合对象,集合参数类型的元素1,集合参数类型的元素2,集合参数类型的元素3.......)
* 用于添加多个属性
* 2.shuffle(),用于随机打乱集合的顺序
* 3.sort()用于排序,默认升序排序,1.但是对于自定义的类 需要 实现Comparable<T>接口,并重写public int compareTo(T o)方法,设置排序方式
* 2.public static <T> void sort(List<T> list, Comparator<? super T> c),如下
* */
public class DemoCollections {
public static void main(String[] args) {
ArrayList<Dog> arrayList = new ArrayList<>();
Dog d1 = new Dog(22);
Dog d2 = new Dog(18);
Dog d3 = new Dog(30);
//利用Collections工具类的addAll()方法存储多个数据
Collections.addAll(arrayList,d1,d2,d3);
//sort()方法的第二种方法
Collections.sort(arrayList, new Comparator<Dog>() {
@Override
public int compare(Dog o1, Dog o2) {
//前面减后面升序,后面减前面降序
return o2.getAge()-o1.getAge();
}
});
System.out.println(arrayList);
}
}
    本人是个刚入职的小菜鸡,写下来只是一些随笔,用来自己回顾,很多东西不一定正确,只是我当下自己的理解,请各位大神,有错误的地方可以指出来哈。
                    
                
                
            
        
浙公网安备 33010602011771号