Collections
-java.utils.Collections是集合工具类,用来对集合进行操作。部分方法如下:
-public static <T> boolean addAll(Collection<T> c,T...elements):往集合中添加一些元素
-public static void shuffle(list<?> list)打乱顺序:打乱集合顺序
-public static <T> void sort(List<T> list):将集合中元素按照默认规则排序。
*sort(List<T> list)使用前提:
被排序的集合里面存储的元素,必须实现Comparable,重写接口中的方法compareto定义排序规则
Comparable接口的排序规则:
自己(this)-参数 是升序
public class DemoCollections {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c", "d", "e");
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
System.out.println("========================");
ArrayList<Integer> list2 = new ArrayList<>();
Collections.addAll(list2,1,234,2,432,223,12);
Collections.sort(list2);
System.out.println(list2);
System.out.println("========================");
Person p1 = new Person("古力娜扎",18);
Person p2 = new Person("刘亦菲",15);
Person p3 = new Person("张柏芝",25);
ArrayList<Person> list3 = new ArrayList<>();
Collections.addAll(list3,p1,p2,p3);
System.out.println(list3);
Collections.sort(list3);
System.out.println(list3);
}
}
Person类
public int compareTo(Person o) {
return this.age-o.age;
}
java.utils.Collections
另一种sort方法
-public static T void sort(List<T> list, Comparator<? super T>):将集合中元素按照制定规则排序
Comparator和Comparable的区别:
Comparable:自己(this)和别人(参数)比较,自己需要实现Comparable接口,重写比较的规则CompareTo方法
Comparator:相当于找一个第三方的裁判,比较两个元素的大小
public class DemoCollections {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c", "d", "e");
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
System.out.println("========================");
ArrayList<Integer> list2 = new ArrayList<>();
Collections.addAll(list2,1,234,2,432,223,12);
Collections.sort(list2);
System.out.println(list2);
System.out.println("========================");
Person p1 = new Person("古力娜扎",18);
Person p2 = new Person("刘亦菲",15);
Person p3 = new Person("张柏芝",25);
ArrayList<Person> list3 = new ArrayList<>();
Collections.addAll(list3,p1,p2,p3);
System.out.println(list3);
Collections.sort(list3);
System.out.println(list3);
System.out.println("========================");
Collections.shuffle(list3);
System.out.println(list3);
Collections.sort(list3,new Comparator<Person>(){
@Override
public int compare(Person o1, Person o2) {
int result = o1.getAge()-o2.getAge();
if(result==0){
result = o1.getName().charAt(0)-o2.getName().charAt(0);
}
return result;
}
});
System.out.println(list3);
}