JAVA hashmap的用法

1.加入元素2.遍历这个map3.移除元素
2025-04-06 18:54:48
推荐回答(4个)
回答1:

已经给楼主写了个例子..

import java.util.HashMap;
import java.util.HashSet;

import java.util.Iterator;

public class HashMapTest {

public static void main(String[] args){
HashMap hm=new HashMap();

People p1=new People();
People p2=new People();
People p3=new People();
People p4=new People();

hm.put("People3", p1);
hm.put("People1", p2);
hm.put("People4", p3);
hm.put("People2", p4);

Iterator it=hm.keySet().iterator();

while(it.hasNext()){
System.out.println(it.next());
}
}
}
class People {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

运行了没问题..

祝楼主早日成功!

回答2:

//distHosts是一个HashMap
Iterator
itr
=
this.distHosts.values().iterator();
while
(itr.hasNext())
{
Host
host
=
(Host)
itr.next();
logger.info("从主机列表中取得主机,其地址为:
"
+
host.getHost());
******
也许对你有帮助,现在还没有研究其API

回答3:

你的类是自己的类,必需有自己的get方法.而你没有。
在此看来是hash的一个方法。而不是你自己的方法。
即为hash.get()方法。而你写成那样是错的。

回答4:

Iterator it = hm.keySet().iterator(); 这行代码是什么意思?