1. 程式人生 > >Java中Map和Set之間的關係(及Map.Entry)

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());
			}
		
		
	}
	
	
	
	
	
}

輸出結果為: