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

1、通过查找API文档:

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





3、Map.entrySet( )返回的是一个collection集合,并且,这个collection中的元素是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());
			}
		
		
	}
	
	
	
	
	
}

输出结果为:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值