package cn.learn.collection.Collections;
/*
排序的对象的类,实现comparable借口,重写compareto方法
若要打印必须重写toString方法,会默认调用
*/
public class Person implements Comparable<Person>{
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重写排序方法
@Override
public int compareTo(Person o) {
return this.getAge() - o.getAge();//年龄升序排序
//return 0;//认为元素都是相同的
}
}
1 package cn.learn.collection.Collections;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Collections;
6 import java.util.Comparator;
7
8 /*
9 java.util.Collections是集合工具类
10
11 注意:sort(List<T> list)使用前提
12 被排序的集合里面存储的元素,若不符合java里面自带的方法,是自定义类型
13 需要在一般是生成对象的类中
14 实现Comparable,重写Compareto定义排序规则
15 o - this 降序
16
17 sort(List<E>,Comparator<? super T>)
18 Comparable与Comparator的区别
19 Comparable:自己(this)和别人(参数)比较,需要自己在类中重写comparTo方法
20 Comparator:相当于找一个第三方的裁判,比较两个 ,是一个接口 ,重写内部类
21
22
23
24 */
25 public class CollectionsApi {
26 public static void main(String[] args) {
27 ArrayList<Integer> num = new ArrayList<>();
28 num.add(5);
29 num.add(8);
30 num.add(7);
31 num.add(27);
32 //太麻烦,可以用集合工具类,添加多个元素,返回的是Boolean值
33 Collections.addAll(num,5,6,8,12);
34 System.out.println(num);//[5, 8, 7, 27, 5, 6, 8, 12]
35
36 //shuffle(弄混)方法,打乱集合顺序
37 Collections.shuffle(num);
38 System.out.println(num); //[8, 12, 27, 5, 5, 7, 6, 8]
39
40 //sort集合排序,默认升序
41 Collections.sort(num);
42 System.out.println(num); //[5, 5, 6, 7, 8, 8, 12, 27]
43
44 //如果不是字符和整数,对对象进行排序,需要重写排序方法
45 //根据年龄进行升序排序
46 ArrayList<Person> people=new ArrayList<>();
47 people.add(new Person("ap",12));
48 people.add(new Person("nha",16));
49 people.add(new Person("nihp",10));
50 people.add(new Person("hp",10));
51 Collections.sort(people); //排序
52 System.out.println(people);
53
54
55 //sort(List<E>,Comparator<? super T>)
56 Collections.sort(people, new Comparator<Person>() {
57 //重写比较规则,降序
58 @Override
59 public int compare(Person o1, Person o2) {
60 //如果年龄一样,比较名字长度升序,年龄降序
61 int age= o2.getAge() - o1.getAge();
62 if(age == 0){
63 age=o1.getName().length()-o2.getName().length();
64 }
65 return age;
66 }
67 });
68 System.out.println(people);
69
70 }
71 }