topic description
sources of topics and their own ideas
my program declares a TreeSet object ts and writes a student class that is considered the same element when the student"s age and name are the same. When the first student object and the last student object are added to the ts, the names and ages of the two student objects are the same, and the print results show that both elements are output with a ts size of 4.
related codes
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<>();
ts.add(new Student("lisi02", 22));
ts.add(new Student("lisi01", 40));
ts.add(new Student("lisi08", 19));
ts.add(new Student("lisi02", 22));
// the first element and the last one are added to ts
// However, ts belongs to a Set Collection.
// So I think the last one should not be added to ts.
// when the second element is annotated, the last one can not be added.
// Can you explain why?
for (Student e : ts) {
System.out.println(e.getName() + "\t...\t" + e.getAge());
}
System.out.println(ts.size());
}
}
class Student implements Comparable {
private String name;
private int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int compareTo(Object obj) {
if (!(obj instanceof Student))
throw new RuntimeException("Not Student class");
Student p = (Student) obj;
// When name and age are the same, the elements are the same
if (this.name.equals(p.getName()) && p.getAge() == this.age) {
System.out.println(name + "..." +age);
return 0;
} else
return 1;
}
}