HashSet存储字符串并遍历
首先来看一段代码:
HashSet<String> hs = new HashSet<String>();
boolean b1 = hs.add("a");
boolean b2 = hs.add("b");
boolean b3 = hs.add("a");
boolean b4 = hs.add("c");
System.out.println(b1+" "+b2+" "+b3+" "+b4);
System.out.println(hs);
true true false true
[b, c, a]
从上面可以看出该类实现了Set接口,不允许出现重复元素,不保证集合中元素的顺序,允许包含值为null的元素,但最多只能一个。
HashSet存储自定义对象保证元素唯一性
HashSet<Person> hs = new HashSet<Person>();
boolean b1 = hs.add(new Person("张三",23));
boolean b2 = hs.add(new Person("张三",23));
boolean b3 = hs.add(new Person("李四",24));
boolean b4 = hs.add(new Person("王五",25));
boolean b5 = hs.add(new Person("李四",24));
System.out.println(b1+" "+b2+" "+b3+" "+b4+" "+b5);
true true true true true
为什么返回的结果全部为true呢?
答案是因为每一个对象的地址不同。
先重写equals()方法试试
public boolean equals(Object obj) {
//System.out.println("1");
Person p = (Person)obj ;
return this.name.equals(p.name) && this.age== p.age;
}
true true true true true
经过调试可以看出,equals方法没有被调用。
试试重写hashCode():
public int hashCode(){
return this.age + this.name.hashCode();
}
当hashCode()返回的是this.name的hashCode数值,代表只有返回的地址相同,才去调用equals()方法。如果相同,则不添加进HashSet。
为了减少equals()方法的调用次数,一般直接生成equals()方法和hashCode()方法。
@Override
public int hashCode() {
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) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) 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;
}
HashSet如何保证元素唯一性的原理
- 1.HashSet原理
- 我们使用Set集合都是需要去掉重复元素的, 如果在存储的时候逐个equals()比较, 效率较低,哈希算法提高了去重复的效率, 降低了使用equals()方法的次数
- 当HashSet调用add()方法存储对象的时候, 先调用对象的hashCode()方法得到一个哈希值, 然后在集合中查找是否有哈希值相同的对象
- 如果没有哈希值相同的对象就直接存入集合
- 如果有哈希值相同的对象, 就和哈希值相同的对象逐个进行equals()比较,比较结果为false就存入, true则不存
- 2.将自定义类的对象存入HashSet去重复
- 类中必须重写hashCode()和equals()方法
- hashCode(): 属性相同的对象返回值必须相同, 属性不同的返回值尽量不同(提高效率)
- equals(): 属性相同返回true, 属性不同返回false,返回false的时候存储