s-day04-TreeSet保存自定义对象
This commit is contained in:
@@ -0,0 +1,41 @@
|
|||||||
|
package com.inmind.treeset02;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class Student implements Comparable<Student>{
|
||||||
|
String name;
|
||||||
|
int age;
|
||||||
|
|
||||||
|
public Student(String name, int age) {
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Student{" +
|
||||||
|
"name='" + name + '\'' +
|
||||||
|
", age=" + age +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
|
||||||
|
Student student = (Student) o;
|
||||||
|
return age == student.age && Objects.equals(name, student.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int result = Objects.hashCode(name);
|
||||||
|
result = 31 * result + age;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(Student o) {
|
||||||
|
return this.age - o.age;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.inmind.treeset02;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
|
||||||
|
/*
|
||||||
|
TreeSet保存自定义对象
|
||||||
|
注意:TreeSet会使用元素的自带的自然排序功能Comparable接口
|
||||||
|
*/
|
||||||
|
public class TreeSetDemo09 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//创建一个对学生对象有排序功能的集合
|
||||||
|
TreeSet<Student> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add(new Student("小王1", 18));
|
||||||
|
treeSet.add(new Student("小王2", 17));
|
||||||
|
treeSet.add(new Student("小王3", 20));
|
||||||
|
System.out.println(treeSet);
|
||||||
|
System.out.println("--------------如果自定义对象没有自然排序或者不符合我们的需求,使用比较器------------------");
|
||||||
|
TreeSet<Student> sets = new TreeSet<>(new Comparator<Student>() {
|
||||||
|
@Override
|
||||||
|
public int compare(Student o1, Student o2) {
|
||||||
|
return o2.age - o1.age;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
sets.add(new Student("小王1", 18));
|
||||||
|
sets.add(new Student("小王2", 17));
|
||||||
|
sets.add(new Student("小王3", 20));
|
||||||
|
System.out.println(sets);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user