问题描述
publicclassTeacherimplementsComparable<Teacher>{privateStringname;privateintage;privatedoublesalary;privateDatebirth;publicTeacher(Stringname,intage,doublesalary,Datebirth){super();this.name=name;this.age=age;this.salary=salary;this.birth=birth;}@OverridepublicStringtoString(){SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");return"Teacher[name="+name+",age="+age+",salary="+salary+",birth="+sdf.format(birth)+"]";}@OverridepublicinthashCode(){finalintprime=31;intresult=1;result=prime*result+age;result=prime*result+((name==null)?0:name.hashCode());returnresult;}@Overridepublicbooleanequals(Objectobj){if(this==obj)returntrue;if(obj==null)returnfalse;if(getClass()!=obj.getClass())returnfalse;Teacherother=(Teacher)obj;if(age!=other.age)returnfalse;if(name==null){if(other.name!=null)returnfalse;}elseif(!name.equals(other.name))returnfalse;returntrue;}publicstaticvoidmain(String[]args)throwsParseException{//TODOAuto-generatedmethodstubTreeSet<Teacher>ts=newTreeSet<Teacher>();SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");Teachert1=newTeacher("lsy",29,5000,sdf.parse("1993-09-11"));Teachert2=newTeacher("lqq",29,5000,sdf.parse("1993-09-23"));Teachert3=newTeacher("rsh",29,5000,sdf.parse("1993-06-06"));ts.add(t1);ts.add(t2);ts.add(t3);System.out.println(ts);}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}publicdoublegetSalary(){returnsalary;}publicvoidsetSalary(doublesalary){this.salary=salary;}publicTeacher(){super();}publicDategetBirth(){returnbirth;}publicvoidsetBirth(Datebirth){this.birth=birth;}@OverridepublicintcompareTo(Teachert){//TODOAuto-generatedmethodstubif(this.salary==t.salary){if(this.age==t.age){return0;}else{return(int)(this.age-t.age);}}else{return(int)(this.salary-t.salary);}}}
解决方案
解决方案二:
遍历一下看看
解决方案三:
遍历了还是一个对象,并且我输出tm.size()的值是1怎么回事
解决方案四:
关于javabean中hashCode()和equals方法的解析
解决方案五:
因为年龄和工资一样的话无法排序导致put不成功。建议你这样改下:@OverridepublicintcompareTo(Teachert){if(this.salary==t.salary){if(this.age==t.age){returnthis.name.compareToIgnoreCase(t.name);}else{return(int)(this.age-t.age);}}else{return(int)(this.salary-t.salary);}}
解决方案六:
还是没出先我想要的结果诶我是想让只要名字跟出生日期一样就让它是同一个对象按你的这样改完以后如果两个对象的名字跟出生日期一样而salary跟age其中有一个不一样它还会按两个对象处理啊怎么