软件编程
位置:首页>> 软件编程>> java编程>> 浅谈Java中Map和Set之间的关系(及Map.Entry)

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

作者:G_66  发布时间:2023-08-25 02:23:48 

标签:Java,Map,Set,Map.Entry

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)

来源:https://blog.csdn.net/G_66_hero/article/details/70177423

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com