Map接口的使用注意事项
来源:互联网 发布:ubuntu拷贝文件 编辑:程序博客网 时间:2024/06/05 22:39
注意事项一:不能直接使用迭代输出Map中的全部内容
使用迭代进行输出的步骤:
- 将Map接口的实例通过entrySet()方法变为Set接口对象。
- 通过Set接口实例为Iteratr实例化。
- 通过Iterator迭代输出,每个内容都是Map.Entry的对象。
- 通过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));
}
}
输出结果:
- Map接口的使用注意事项
- Map接口的使用注意事项
- 使用接口的注意事项
- 接口使用的注意事项
- map、string使用的注意事项
- Map接口的使用。。。
- Map接口的使用
- Java类集框架——Map接口使用注意事项
- 关于Map使用时的注意事项
- std::map 使用注意事项
- STL MAP使用注意事项
- COM接口指针使用的注意事项
- .NET 中接口使用时的注意事项
- 使用HBase Shell 接口的注意事项
- Java类集 _Map 接口的使用注意事项
- 集合框架中的Map接口的使用
- JAVA中接口 Map.Entry的使用
- 接口java.util.Map.Entry的使用
- [微信小程序]计算自己手机到指定位置的距离
- leetcode 73. Set Matrix Zeroes
- 第九周项目3-利用二叉树遍历思想解决问题(2)
- MySQL 日期时间
- linux cut用法
- Map接口的使用注意事项
- java打jar包需要注意的事项
- VMware虚拟磁盘VMDK格式说明书1.1---3 The Descriptor File描述文件
- Appium新版本不再支持ByName定位了怎么办
- HttpClient androidStudio中的基础使用
- SQLCipher的异常总结
- 沉浸式状态栏
- 图片转PDF,图片过长智能截取
- 2017中国国际教育装备博览会会刊(参展商名录)