您的位置:首页技术文章
文章详情页

浅谈Java中Map和Set之间的关系(及Map.Entry)

【字号: 日期:2022-08-24 09:43:06浏览:7作者:猪猪

1、通过查找API文档:

浅谈Java中Map和Set之间的关系(及Map.Entry)

2、Map.Entry是一个接口,所以不能直接实例化。

浅谈Java中Map和Set之间的关系(及Map.Entry)

3、Map.entrySet( )返回的是一个collection集合,并且,这个collection中的元素是Map.Entry类型,如下图所示:

浅谈Java中Map和Set之间的关系(及Map.Entry)

浅谈Java中Map和Set之间的关系(及Map.Entry)

4、

Map是Java中的接口,Map.Entry是Map的一个内部接口。java.util.Map.Entry接口主要就是在遍历map的时候用到。

Map提供了一些常用方法,如keySet()、entrySet()等方法,keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为Map.Entry。

Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。

package Demo;import java.util.*;import java.util.Map.*; public class DemoMap { public static void main(String[] args) { text1(); System.out.println('========================================================='); text2(); } public static void text1(){ Map<Integer,String> DemoMap=new HashMap<Integer,String>(); DemoMap.put(4, 'dddd'); DemoMap.put(1, 'a'); DemoMap.put(3, 'ccc'); DemoMap.put(2, 'bb'); Collection<Map.Entry<Integer,String>> set=DemoMap.entrySet(); System.out.println('set=='+set); Iterator<Map.Entry<Integer, String>> it=set.iterator(); Map.Entry<Integer,String> entry; while(it.hasNext()){ entry=it.next(); System.out.println('en.getKey()=='+entry.getKey()); System.out.println('en.getValue()=='+entry.getValue()); } } public static void text2(){ Map<Integer,String> DemoMap=new LinkedHashMap<Integer,String>(); DemoMap.put(4, 'dddd'); DemoMap.put(1, 'a'); DemoMap.put(3, 'ccc'); DemoMap.put(2, 'bb'); Iterator<Entry<Integer,String>> set=DemoMap.entrySet().iterator(); Entry<Integer,String> temp; while(set.hasNext()){ temp=set.next(); System.out.println('getKey()=='+temp.getKey()); System.out.println('getValue()=='+temp.getValue()); } } }

输出结果为:

浅谈Java中Map和Set之间的关系(及Map.Entry)

以上这篇浅谈Java中Map和Set之间的关系(及Map.Entry)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Java
相关文章: