* HashSet:底层使用的数据结构是哈希表,线程不安全的
* 保证对象是唯一的方法:int hashCode() boolean equal(Object obj)
* 在添加对象时先用对象的的哈希值和集合中对象的哈希值分别比较,
* 如果和集合 中所有的对象哈希值都不相同,那么直接诶把对象加入集合。
* 如果出现哈希值相同的,那么再调用equal方法对象哈希值相同的两个对象进行比较,
* 如果equal方法返回true则认为是同一对象,不把该对象加入集合,否则认为是不同的对象,加入集合 *
*
*案例①:
* */
package com.jh;
import java.util.*;
class Personhs
{
public int hashCode()
{
return 66;
}
//调用的是重写之后的值,最后返回true的只有一个了。最
public boolean equals(Object obj)
{
return true;
}
}
public class TestHashSet {
public static void main(String[] args) {
//在使用add方法添加对象时保证了对象是唯一的
HashSet hs=new HashSet();
// hs.add("java01");
// hs.add("java02");
// hs.add("java01");
// sop(hs);//[java02, java01]如果对象重复,后者会覆盖前者
//如下是输出3个对象,并不是输出一个。(注意重写了equals方法后输出的是一个了)
hs.add(new Personhs());
hs.add(new Personhs());
hs.add(new Personhs());
sop(hs);//[com.jh.Personhs@7852e922, com.jh.Personhs@15db9742, com.jh.Personhs@6d06d69c]
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
//案例②
package com.jh;
import java.util.*;
class Studenths2
{
private String name;
private int age;
public Studenths2(){}
public Studenths2(String name ,int age)
{
this.name=name;
this.age=age;
}
//hashSet依据方法1,写如下返回哈希值,在判断即可
public int hashCode()
{
return name.hashCode()+age*36;//*36减少哈希值相同的概率
}
///hashSet依据方法2,返回哈希值,在判断即可,如果相同就返回true,返回相同的就不会添加进去的
public boolean equals(Object obj)
{
if(!(obj instanceof Studenths2))
{
throw new ClassCastException("类型转换异常");
}
Studenths2 stu2=(Studenths2)obj;
return this.name.equals(stu2.name) && this.age==stu2.age;
}
public String toString()
{
return name+","+age;
}
}
public class TestHashSet2 {
public static void main(String[] args) {
HashSet hs=new HashSet();
hs.add(new Studenths2("yoti",27));
hs.add(new Studenths2("wangsi",24));
hs.add(new Studenths2("zhangsan",20));
hs.add(new Studenths2("yoti",27));
// sop(hs);//[zhangsan,20, yoti,27, wangsi,24]
//如下是迭代器,直接写如下,会添加重复的。
Iterator ite=hs.iterator();
while(ite.hasNext())
{
Object obj=ite.next();
sop(obj);
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}