Map接口的使用注意事项

来源:互联网 发布:ubuntu拷贝文件 编辑:程序博客网 时间:2024/06/05 22:39

注意事项一:不能直接使用迭代输出Map中的全部内容

使用迭代进行输出的步骤:

  1. Map接口的实例通过entrySet()方法变为Set接口对象。
  2. 通过Set接口实例为Iteratr实例化。
  3. 通过Iterator迭代输出,每个内容都是Map.Entry的对象。
  4. 通过Map.Entry进行key-->value的分离。

Map输出方式一、Iterator输出Map

 

importjava.util.HashMap;

importjava.util.Iterator;

importjava.util.Map;

importjava.util.Set;

publicclass outPutMap1 {

publicstatic void main(String[] args) {

Map<String,String> map = null;

map= new HashMap<String, String>();

map.put("mldn","www.mldn.cn");

map.put("zhinangtuan","www.zhinangtuan.net.cn");

map.put("mldnjava","www.mldnjava.com");

Set<Map.Entry<String,String>> allset = null;

allset= map.entrySet();

Iterator<Map.Entry<String,String>> iterator = allset.iterator();

while(iterator.hasNext()) {

Map.Entry<String,String> mEntry = iterator.next();

System.out.println(mEntry.getKey()+ "------->" + mEntry.getValue());

}

}

}

输出结果:


 

Map输出方式二:foreach输出Map

importjava.util.HashMap;

importjava.util.Map;

public classoutPutMap {

publicstatic void main(String[] args) {

Map<String,String> map = null;

map= new HashMap<String, String>();

map.put("mldn","www.mldn.cn");

map.put("zhinangtuan","www.zhinangtuan.net.cn");

map.put("mldnjava","www.mldnjava.com");

for(Map.Entry<String, String> me : map.entrySet()) {

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<Person,String> map = null;

map= new HashMap<Person, String>();

Person per1 = new Person("张三",30);

Person per2 = new Person("张三",30);

map.put(per1,"zhangsan");

System.out.println(map.get(per2));

}

}

输出结果:

 


原创粉丝点击