HashSet和HashMap (二)

2014-11-24 11:33:16 · 作者: · 浏览: 12

V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}

modCount++;
addEntry(hash, key, value, i);//优雅地将新Entry加至链头。Entry是HashMap的内部类。具体请阅读jdk源码。
return null;
}例子1:


[java]
import java.util.HashSet;
import java.util.Set;

class Name
{
private String first;
private String last;
public Name(String first, String last)
{
this.first = first;
this.last = last;
}
public boolean equals(Object o)
{
if(!(o instanceof Name))
return false;
Name n = (Name)o;
return n.first.equals(first) && n.last.equals(last);

}
}

public class HashSetTest
{
public static void main(String[] args)
{
Set s = new HashSet();
s.add(new Name("zhang","3"));
System.out.println(s.contains(new Name("zhang", "3"))); //false

}
}

import java.util.HashSet;
import java.util.Set;

class Name
{
private String first;
private String last;
public Name(String first, String last)
{
this.first = first;
this.last = last;
}
public boolean equals(Object o)
{
if(!(o instanceof Name))
return false;
Name n = (Name)o;
return n.first.equals(first) && n.last.equals(last);

}
}

public class HashSetTest
{
public static void main(String[] args)
{
Set s = new HashSet();
s.add(new Name("zhang","3"));
System.out.println(s.contains(new Name("zhang", "3"))); //false

}
}程序将输出false是因为HashSet判断是否“相等”的标准除了要求通过equals方法返回true外,还要求两个对象的HashCode()返回值相等,且这两个方法的返回值保持一致。通常来说,所有参与hashCode()计算的关键属性都应作为equals方法比较的标准(参见上一篇Java中hashcode和equals方法)。

例子2

[java]
import java.util.HashSet;
import java.util.Set;

class Name
{
private String first;
private String last;
public Name(String first, String last)
{
this.first = first;
this.last = last;
}
public boolean equals(Object o)
{
if(!(o instanceof Name))
return false;
Name n = (Name)o;
return n.first.equals(first);

}
@Override
public int hashCode()
{
return first.hashCode();
}
@Override
public String toString()
{
return "Name[" + first + ", " + last + "]";
}
}

public class HashSetTest2
{
public static void main(String[] args)
{
Set s = new HashSet();
s.add(new Name("zhang","3"));
s.add(new Name("zhang","4")); //无法覆盖
System.out.println(s); //输出 [Name[zhang, 3]]

}