淺談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()); } } }
輸出結果為:
以上這篇淺談Java中Map和Set之間的關系(及Map.Entry)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. react axios 跨域訪問一個或多個域名問題2. JSP實現文件上傳功能3. python基于socket模擬實現ssh遠程執行命令4. css進階學習 選擇符5. Nodejs 連接 mysql時報Error: Cannot enqueue Query after fatal error錯誤的處理辦法6. 解決python腳本中error: unrecognized arguments: True錯誤7. ASP基礎入門第三篇(ASP腳本基礎)8. ASP基礎知識Command對象講解9. 基于python計算滾動方差(標準差)talib和pd.rolling函數差異詳解10. Ajax對xml信息的接收和處理操作實例分析
