HashMap和HashSet

Map和Set都是接口,他们的定义都必须使用TreeMap,TreeSet或HashMap,HashSet来实现。
例:
Map map = new HashMap();
Set set = new HashSet();
Map、Set与数组的区别
Map存储的是键值对,Set存储的是一个值,但是数组存储的值按照特定的位置存放,Set和Map存放的位置都是 类里面内置好的,并且Map里面的Key是唯一的,Set也不会具有重复的元素,若相同,后定义的元素会覆盖先定义的元素。

下面来说说访问Map里面key,value的方法吧:
1.访问键:

for (String key : map.keySet()) {   //map是已经定义好的Map
            System.out.println(key);
        }

2.访问值:

 for (String v : map.values()) {//map是已经定义好的Map
            System.out.println(v);
        }

3.访问所有的键值对:

//map是已经定义好的Map
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
        }

访问Set需要使用迭代器对象:Iterator

   Iterator<String> it = set.iterator();   //set是已经定义好的Set
        while (it.hasNext()) {
            System.out.println(it.next());
        }
 

你可能感兴趣的:(HashMap和HashSet)