HashMap

来源:互联网 发布:怎样与淘宝买家联系 编辑:程序博客网 时间:2024/06/02 05:29
HadhMap:底层是哈希表数据结构,允许存入null键null值,不同步,jdk1.2,效率高
Map集合的两种取出方式:
方法一:Set<k> keySet():将map集合中所有的键存入到Set集合中,由于set具备迭代器,
        所以可以用迭代的方式取出所有的键,在使用get方法获取每一个键对应的值
方法二 : Set<Map.Entry<k,v>> entrySet() : 将map集合中的映射关系Map.Entry存入到set集合中,
然后使用迭代的方式取出映射关系关系entrySet(),在使用关系的getKey()和getValue()方法获取


Map.Entry: 其实Entry也是一个接口,他是Map接口中的一个内部接口
方法二原理: 
interface Map{public static interface Entry{public abstract Object getKey();public abstract Object getValue();}}class HashMap implements Map{class Hash implements Entry{public Object getKey(){}public Object getValue(){}}}public class HashMapDemo {public static void main(String[] args) {HashMap<String,String> map = new HashMap<String,String>();map.put("01","zhangsan1");map.put("03","zhangsan3");map.put("04","zhangsan4");map.put("02","zhangsan2");map.put("02","sdfasdfsad");方法一:// 先使用KeySet()获取map集合的所有键的Set集合Set<String> s = map.keySet();//获取Set集合的迭代器Iterator<String> it = s.iterator();while(it.hasNext()){String key = it.next();//根据键值,使用map集合的get方法获取其对应的valueString value = map.get(key);System.out.println(value);}方法二:// 将Map集合中的映射关系取出,存入到Set集合中Set<Map.Entry<String, String>> s =map.entrySet();Iterator<Map.Entry<String, String>> it = s.iterator();while(it.hasNext()){Map.Entry<String, String> me = it.next();System.out.print(me.getKey());System.out.println(me.getValue());}}}


原创粉丝点击