Java基本功:容器Map

版权声明:转载请说明去处,文章仅供学习参考 https://blog.csdn.net/qq_38487155/article/details/86509789

目录

 

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的三种遍历

		//遍历方式:由于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()用来返回子树。

猜你喜欢

转载自blog.csdn.net/qq_38487155/article/details/86509789