Objects in the treeset are sorted by size. Therefore, objects in the treeset must be comparable in size.
① The comparable interface can be inherited through objects in the treeset.
② Determine the object size through external referers
According to the rules of the custom comparator, when the comparison objects are the same, they are considered to be the same elements in content or logic, and they will not be added.
Method 1: implement the comparable Interface
package cn.cqu.huang;
import java.util.Set;
import java.util.TreeSet;
class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return name+":"+age;
}
@Override
public int compareTo(Student stu) {
int t = name.compareTo(stu.name);
If (T! = 0) return t; // The result is returned directly if the comparison is successful.
Return this. Age-Stu. Age; // when T is 0, it indicates that the name is the same, so we need to further differentiate the size based on age.
}
}
public class TreeSetDemo {
public static void main(String[] args) {
Set<Student> set = new TreeSet<Student>();
set.add(new Student("huang",10));
set.add(new Student("huang",20));
set.add(new Student("he",10));
set.add(new Student("huang",10));
set.add(new Student("yi",20));
System.out.println(set);
}
}
// Method 2: Use the referee class
package cn.cqu.huang;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
class Student {
private String name;
private int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String toString(){
return name+":"+age;
}
}
// ------------------ Referee class
class K implements Comparator{
@Override
public int compare(Object obj1, Object obj2) {
if(obj1 instanceof Student ==false || obj2 instanceof Student == false)
return 0;
Student s1 = (Student) obj1;
Student s2 = (Student) obj2;
int t = s1.getName().compareTo(s2.getName());
If (T! = 0) return t; // t is not 0, indicating that the name is different and the result has been compared.
Return s1.getage ()-s2.getage (); // if the name is the same, the age is further compared.
}
}
public class TreeSetDemo {
public static void main(String[] args) {
Set <student> set = new treeset <student> (new K (); // input a referee when constructing a treeset.
set.add(new Student("huang",10));
set.add(new Student("huang",20));
set.add(new Student("he",10));
set.add(new Student("huang",10));
set.add(new Student("yi",20));
System.out.println(set);
}
}