Java基本功:容器Map

百般思念 提交于 2019-11-28 15:08:37

原文引用 大专栏  https://www.dazhuanlan.com/2019/08/26/5d63503004632/

目录

Map:一个键值(key)对应一个对象(value)的容器接口,并且没有排序

Map的三种遍历

Entry对象(键值对对象):在获得entrySet()返回的Set对象必须声明Entry类型,value>

HashMap:哈希算法 ,同样需要实现HashCode()和equals()方法

TreeMap:和TreeSet类似,红黑树结构,同样进行排序(次序由存入TreeMap的类的compare()或compareTo()方法决定,也就是说装入TreeMap的类必须实现HashCode(),equals(),compare()三个方法),同时TreeMap还有一个subMap()用来返回子树。

Map:一个键值(key)对应一个对象(value)的容器接口,并且没有排序

Map的三种遍历

123456789101112131415161718192021222324252627
	//遍历方式:由于Map没有提供iterator()函数,而是用keySet(),values()和entrySet()三个方法取代//方法一Collection<String> c=m.values();for(Iterator<String> it=c.iterator();it.hasNext();) {	System.out.print(it.next()+" ");}System.out.println();//方法二Set<Integer> s=m.keySet();for(Iterator<Integer> it=s.iterator();it.hasNext();) {	System.out.print(it.next()+" ");}System.out.println();//方法三/* * Entry对象:把键值当成一个对象,用来转换Map与其它容器(Set)容器的参数不匹配问题 * 也提供了获取键,值,以及设置值的方法 * getKey():获取当前键值对里的键 * getValue():获取当前键值对里的值 * setValue(V):重新设置当前键值对里的值 */Set<Entry<Integer,String>> set=m.entrySet();for(Iterator<Entry<Integer,String>>it=set.iterator();it.hasNext();) {	/*Entry<Integer,String> e=it.next();	System.out.print(e.getKey()+"---->"+e.getValue()+"  ");*/	System.out.println(it.next()+" ");}

Entry对象(键值对对象):在获得entrySet()返回的Set对象必须声明Entry<Key,Value>类型

HashMap:哈希算法 ,同样需要实现HashCode()和equals()方法

TreeMap:和TreeSet类似,红黑树结构,同样进行排序(次序由存入TreeMap的类的compare()或compareTo()方法决定,也就是说装入TreeMap的类必须实现HashCode(),equals(),compare()三个方法),同时TreeMap还有一个subMap()用来返回子树。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!