import java.util.*;
class HashCodeDemo
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add(new Person("a1",11));
hs.add(new Person("a2",12));
hs.add(new Person("a3",13));
hs.add(new Person("a4",14));
Iterator it=hs.iterator();
//sop(hs.contains(new Person("a2",12)));
hs.remove(new Person("a2",12));//怎么出现错误了呢????求解
while (it.hasNext())
{
Person p =(Person)it.next();
sop(p.getName()+"+++"+p.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class Person
{
private String name;
private int age;
Person (String name,int age)
{
this.name=name;
this.age=age;
}
public int hashCode()//根据对象条件建立哈希值。描述事物需要往集合里存事物都要复写
{
System.out.println(this.name+"....hashCode");
return name.hashCode()+age*39;//乘以一个数值返回来一个值随意
}
public boolean equals(Object obj)//覆盖这个方法
{
if (!(obj instanceof Person))
return false;
Person p=(Person)obj;
System.out.println(this.name+".equals..."+p.name);
return this.name.equals(p.name)&&this.age==p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
出现错误
a1....hashCode
a2....hashCode
a3....hashCode
a4....hashCode
a2....hashCode
a2.equals...a2
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at HashCodeDemo.main(HashCodedDemo.java:23)
没用HashCode用ArrayList就可以调用equals,用HashCode就要自己根据对象条件建立哈希值。有什么不同呢???
|