黑马程序员技术交流社区
标题:
TreSet判断元素是否唯一的方式:
[打印本页]
作者:
AndyYuan
时间:
2015-8-28 08:32
标题:
TreSet判断元素是否唯一的方式:
public class TreeSetTest {
public static void main(String[] args){
TreeSet<Student> set = new TreeSet<Student>();
Student stu1 = new Student("zhangsan",10) ;
Student stu2 = new Student("zhangsan",11) ;
Student stu3 = new Student("lisi",10) ;
Student stu4 = new Student("wangwu",20) ;
set.add(stu1);
set.add(stu2);
set.add(stu3);
set.add(stu4);
for(Student stu :set){
System.out.println(stu);
}
System.out.println("---------------------------");
TreeSet<Student> set2 = new TreeSet<Student>(new MyComparator());
set2.add(stu1);
set2.add(stu2);
set2.add(stu3);
set2.add(stu4);
for(Student stu :set2){
System.out.println(stu);
}
}
}
/*
* 自定义的比较器类
* 实现Comparator接口,从写,conpare()方法
* 按年龄排序,年龄相同,按姓名排序
*/
class MyComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2 ;
int temp = s1.getage()-s2.getage();
return temp==0?s1.getname().compareTo(s2.getname()):temp;
}
}
class Student implements Comparable{
int age ;
String name ;
public Student(String name ,int age){
this.age = age ;
this.name = name ;
}
public String getname(){
return name;
}
public int getage(){
return age;
}
//Student本身的比较方法
//先按姓名排序,姓名相同,按年龄排序
@Override
public int compareTo(Object o) {
System.out.println(this.name+"..compareTo.."+((Student) o).getname());
int temp = this.name.compareToIgnoreCase(((Student) o).getname());
return temp== 0?this.age-((Student) o).getage():temp;
}
@Override
public int hashCode() {
System.out.println(this.name+" hash code..");
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println(this.name+"..equals.."+((Student) obj).getname());
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "[name=" + name + ",age=" + age + "]";
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2