Collections工具类
主要有四个方法:
- public static boolean addAll(Collection c, T… elements) `:
- 往集合中添加一些元素。
- public static void shuffle(List<?> list):
- 打乱集合顺序。
- public static void sort(List list):
- 将集合中元素按照默认规则排序。
- public static void sort(List list,Comparator<? super T> )`:
- 将集合中元素按照指定规则排序。
- 1.T…elements->可变参数
- 2.与<?>二者都是适配符,前者可以用于方法内部,后者只能用于传参
- 3.sort函数是对指定的元素按照默认规则进行排序,如字符串或整形都是按照从小到大的顺序。
- 是因为字符串或封装类继承了Compareable<>接口,且重写了compareTo函数,该函数是规定排序规则的函数.
- Collection.sort(list)会自动调用compareTo,如果没有这句,list是不会排序的
- 该方法的返回值如果是自己(this)-参数:升序
- 0:认为都相等
- 参数-this:降序
- 4.https://www.cnblogs.com/drizzlewithwind/p/6100164.html对于<? super T>的解释
- Comparator与Compareable不同,Compareable是比较自己和别人大小
- 而CompareComparator是比较别人和别人大小
- 由方法Compare实现
-返回值为 前面-后面时候:升序;
后面减前面:降序;
为0:相等;
public class TestMain {
public static void main(String[] args) {
List<Integer> list=new ArrayList();
list.add(1);
list.add(3);
list.add(2);
System.out.println(list);
Collections.sort(list,new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
System.out.println(list);
}
}