我的程序里声明了一个 TreeSet 对象 ts,写了一个学生类,当学生的年龄和姓名相同时被认为是相同元素。在 ts 中添加了第一个学生对象与最后一个学生对象时,使这俩个学生对象的姓名和年龄相同,打印结果发现这俩个元素均被输出,ts 大小为 4。
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;
}
}
哆啦的时光机
LEATH
相关分类