注意事项一:不能直接使用迭代输出Map中的全部内容
使用迭代进行输出的步骤:
Map输出方式一、Iterator输出Map:
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.Set;
publicclass outPutMap1 {
publicstatic void main(String[] args) {
Map
map= new HashMap
map.put("mldn","www.mldn.cn");
map.put("zhinangtuan","www.zhinangtuan.net.cn");
map.put("mldnjava","www.mldnjava.com");
Set
allset= map.entrySet();
Iterator
while(iterator.hasNext()) {
Map.Entry
System.out.println(mEntry.getKey()+ "------->" + mEntry.getValue());
}
}
}
输出结果:
Map输出方式二:foreach输出Map
importjava.util.HashMap;
importjava.util.Map;
public classoutPutMap {
publicstatic void main(String[] args) {
Map
map= new HashMap
map.put("mldn","www.mldn.cn");
map.put("zhinangtuan","www.zhinangtuan.net.cn");
map.put("mldnjava","www.mldnjava.com");
for(Map.Entry
System.out.println(me.getKey()+"------>"+me.getValue());
}
}
}
输出结果:
注意事项二:直接使用非系统类作为key,需要覆写改非系统类的equals()和hashCode()方法
importjava.util.HashMap;
importjava.util.Map;
class Person {
privateString name;
privateint age;
publicPerson(String name, int age) {
this.age= age;
this.name= name;
}
@Override
publicboolean equals(Object obj) {
if(this == obj) {
returntrue;
}
if(!(obj instanceof Person)) {
returnfalse;
}
Personp = (Person) obj;
if(this.name.equals(p.name) && this.age == p.age) {
returntrue;
}else {
returnfalse;
}
}
@Override
publicint hashCode() {
returnthis.name.hashCode() * this.age;
}
publicString toString() {
return "姓名:" + this.name + ";年龄"+ this.age;
}
}
public classoutPutMap {
publicstatic void main(String[] args) {
Map
map= new HashMap
Person per1 = new Person("张三",30);
Person per2 = new Person("张三",30);
map.put(per1,"zhangsan");
System.out.println(map.get(per2));
}
}
输出结果: