题目描述题目来源及自己的思路我的程序里声明了一个TreeSet对象ts,写了一个学生类,当学生的年龄和姓名相同时被认为是相同元素。在ts中添加了第一个学生对象与最后一个学生对象时,使这俩个学生对象的姓名和年龄相同,打印结果发现这俩个元素均被输出,ts大小为4。相关代码importjava.util.TreeSet;publicclassTreeSetDemo{publicstaticvoidmain(String[]args){TreeSetts=newTreeSet<>();ts.add(newStudent("lisi02",22));ts.add(newStudent("lisi01",40));ts.add(newStudent("lisi08",19));ts.add(newStudent("lisi02",22));//thefirstelementandthelastoneareaddedtots//However,tsbelongstoaSetCollection.//SoIthinkthelastoneshouldnotbeaddedtots.//whenthesecondelementisannotated,thelastonecannotbeadded.//Canyouexplainwhy?for(Studente:ts){System.out.println(e.getName()+"\t...\t"+e.getAge());}System.out.println(ts.size());}}classStudentimplementsComparable{privateStringname;privateintage;Student(Stringname,intage){this.name=name;this.age=age;}publicStringgetName(){returnname;}publicintgetAge(){returnage;}publicintcompareTo(Objectobj){if(!(objinstanceofStudent))thrownewRuntimeException("NotStudentclass");Studentp=(Student)obj;//Whennameandagearethesame,theelementsarethesameif(this.name.equals(p.getName())&&p.getAge()==this.age){System.out.println(name+"..."+age);return0;}elsereturn1;}}你期待的结果是什么?实际看到的错误信息又是什么?
DIEA
相关分类