Collections集合工具类的方法
ArrayList<String> list=new ArrayList<>();
Collections.addAll(list,"a","b","c","d","1","aaa");
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);
package com.mujiachao;
import java.util.Objects;
public class Person implements Comparable<Person> {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(name, person.name) &&
Objects.equals(age, person.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Person o) {
//升序
return this.getAge()-o.getAge();
//降序
// return o.getAge()-this.getAge();
}
}
Person p1 = new Person("张三", 12);
Person p2 = new Person("李四", 8);
Person p3 = new Person("王五", 72);
Person p4 = new Person("赵柳", 15);
Collections.addAll(person,p1,p2,p3,p4);
Collections.sort(person);
System.out.println(person);
实现Comparable接口 重写compareTo()方法
package com.mujiachao;
public class Student {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
ArrayList<Student> students=new ArrayList<>();
Student p1 = new Student("张三", 12);
Student p2 = new Student("a李四", 8);
Student p3 = new Student("b王五", 8);
Student p4 = new Student("赵柳", 15);
Collections.addAll(students,p1,p2,p3,p4);
Collections.sort(students, new Comparator<com.mujiachao.Student>() {
@Override
public int compare(Student o1, Student o2) {
int result=o1.getAge()-o2.getAge();
if (result == 0) {
result=o1.getName().charAt(0)-o2.getName().charAt(0);
}
return result;
}
});
System.out.println(students);
}