HashSet set=new HashSet<>();
//在String内部重写了Hashcode()和equals()方法,通过对这两个方法的调用,实现了去重
set.add("java1");//add方法内部实现了去重,默认调用了String里的Hashcode()和equals()方法实现的元素的去重
set.add("java2");
set.add("java3");
set.add("java4");
set.add("java4");
System.out.println(set);//重写了toString
HashSet set1=new HashSet<>();
set1.add(new Person("bb1",11));
set1.add(new Person("bb2",11));
set1.add(new Person("bb3",11));
set1.add(new Person("bb4",11));
set1.add(new Person("bb4",11));
set1.add(new Person("bb5",11));
System.out.println(set1);
class Person{
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return name.hashCode()+age*999;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Person)) {//容错处理
throw new RuntimeException();
}
Person person=(Person)obj;//向下转型
return age==person.age && name.equals(person.name);
}
}
//结果是
[java4, java3, java2, java1]
[Person [name=bb4, age=11], Person [name=bb3, age=11], Person [name=bb5, age=11], Person [name=bb2, age=11], Person [name=bb1, age=11]]
分析:1.Set本身有去重功能是因为String内部重写了hashCode()和equals()方法,在add里实现了去重
而我们模仿这个功能,自己重写hashCode()和equals()方法对 add(new Person("bb5",11))这种进行去重
2.在打印set时,内部重写了toString()与后来我们重写的toString无关,后来重写的toString是为了打印后
面的带对象的添加。
TreeSet
1) Comparable 接口里的 compareTo方法
@Override
@Override
public int compareTo(Object o) {
if(!(o instanceof P)) {
throw new ClassCastException();
}
P p=(P)o;
//例如先比较年龄,再比较姓名
int num = age - p.age;
return num==0?name.compareTo(p.name):num;
}
public class Test1 {
public static void main(String[] args) {
TreeSet set=new TreeSet<>();
//TreeSet在存储字符串的时候可以实现自动的排序去重
//原因:作为元素的字符串实现了Comparable接口的comparaTo(Object obj)方法
//compareTo()实现的是排序和去重
//add方法内部调用了字符串的CompareTo()方法
//默认是字典排序升序排序
set.add("java1");
set.add("java2");
set.add("java4");
set.add("java4");
set.add("java0");
System.out.println(set);
TreeSet set1=new TreeSet();
set1.add(new P("bb1",11));
set1.add(new P("bb2",12));
set1.add(new P("bb3",13));
set1.add(new P("bb4",14));
set1.add(new P("bb4",14));
set1.add(new P("bb5",11));
System.out.println(set1);
}
}
class P implements Comparable{//实现Comparable接口
String name;
int age;
public P(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "P [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Object o) {
if(!(o instanceof P)) {
throw new ClassCastException();
}
P p=(P)o;
//例如先比较年龄,再比较姓名
int num = age - p.age;
return num==0?name.compareTo(p.name):num;
}
}
//结果是
[java0, java1, java2, java4]
[P [name=bb1, age=11], P [name=bb5, age=11], P [name=bb2, age=12], P [name=bb3, age=13], P [name=bb4, age=14]]
2)实现了Comparator接口的类,接口中有比较的方法叫compare(Object obj1,Object obj2)
ublic class Test3 {