HashMap=数组(桶)+链表,同C++中STL中的hashmap
1/遍历方式
第一种:
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
效率高
第二种:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
效率低
HashSet 插入不重复的元素
public class myclass
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add(new Emp("1","zhangsan",45));
hs.add(new Emp("2","lisi",90));
hs.add(new Emp("3","wangwu",67.5f));
hs.add(new Emp("6","zhangsanyi",78.8f));
Iterator it=hs.iterator();
while(it.hasNext())
{ System.out.println(it.next());
}
}
}
class Emp {
private String name;
private float sal;
private String num;
public Emp(String num,String name,float sal)
{ this.num=num;
this.name=name;
this.sal=sal;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public float getSal() { return sal; }
public void setSal(float sal) { this.sal = sal; }
public String getNum() { return num; }
public void setNum(String num) { this.num = num; }
public String toString()
{
return getName() + " - " + getSal() +" - "+getNum();
}
public int hashcode()
{
return (int)sal * name.hashCode();
}
public boolean equals(Emp s)
{
return sal == s.sal && name.equals(s.name) && num.equals(s.num);
}
}
输出:
lisi - 90.0 - 2
zhangsan - 45.0 - 1
wangwu - 67.5 - 3
zhangsanyi - 78.8 - 6