Map结构总结

首先查看源码:Map经常运用到的源码

[java]  view plain copy
  1. /** 
  2.      * Returns a {@code Set} containing all of the mappings in this {@code Map}. Each mapping is 
  3.      * an instance of {@link Map.Entry}. As the {@code Set} is backed by this {@code Map}, 
  4.      * changes in one will be reflected in the other. 
  5.      * 
  6.      * @return a set of the mappings 
  7.      */  
  8.     public Set<Map.Entry<K,V>> entrySet();   
1.  entrySet() 是运用在遍历Map时,返回一个Set<Map.entry<K,V>>对象。Map.entry<K,V> 相当于Map映射中的一个键值对。然后将这个Map.entry<K,V>存放到Set对象里。Set对象的物理存储也是Map实现的,外加有迭代器功能, public Iterator<E> iterator();

[java]  view plain copy
  1. /** 
  2.      * Returns a set of the keys contained in this {@code Map}. The {@code Set} is backed by 
  3.      * this {@code Map} so changes to one are reflected by the other. The {@code Set} does not 
  4.      * support adding. 
  5.      * 
  6.      * @return a set of the keys. 
  7.      */  
  8.     public Set<K> keySet();  

2.keySet(); 将Map中所有的键存入到set集合中。因为set具备迭代器。所有可以迭代方式取出所有的键,再根据get方法。获取每一个键对应的值。 keySet():迭代后只能通过get()取key 

[java]  view plain copy
  1. /** 
  2.      * Returns a {@code Collection} of the values contained in this {@code Map}. The {@code Collection} 
  3.      * is backed by this {@code Map} so changes to one are reflected by the other. The 
  4.      * {@code Collection} supports {@link Collection#remove}, {@link Collection#removeAll}, 
  5.      * {@link Collection#retainAll}, and {@link Collection#clear} operations, 
  6.      * and it does not support {@link Collection#add} or {@link Collection#addAll} operations. 
  7.      * <p> 
  8.      * This method returns a {@code Collection} which is the subclass of 
  9.      * {@link AbstractCollection}. The {@link AbstractCollection#iterator} method of this subclass returns a 
  10.      * "wrapper object" over the iterator of this {@code Map}'s {@link #entrySet()}. The {@link AbstractCollection#size} method 
  11.      * wraps this {@code Map}'s {@link #size} method and the {@link AbstractCollection#contains} method wraps this {@code Map}'s 
  12.      * {@link #containsValue} method. 
  13.      * <p> 
  14.      * The collection is created when this method is called at first time and 
  15.      * returned in response to all subsequent calls. This method may return 
  16.      * different Collection when multiple calls to this method, since it has no 
  17.      * synchronization performed. 
  18.      * 
  19.      * @return a collection of the values contained in this map. 
  20.      */  
  21.     public Collection<V> values();  
3. values(): 方法是获取集合中的所有的值----没有键,没有对应关系,

[java]  view plain copy
  1. /** 
  2.     * {@code Map.Entry} is a key/value mapping contained in a {@code Map}. 
  3.     */  
  4.    public static interface Entry<K,V> {<span style="font-family: Tahoma, 'Microsoft Yahei', Simsun;">}</span>  
4.Map.entry<K,V> 相当于Map映射中的一个键值对。用于遍历map所用
entry用来迭代map
Map<String, String> map = new HashMap<String, String>();
		map.put("111", "aaa");
		map.put("222", "bbb");
		for (Entry<String, String> entry : map.entrySet()) {
			System.out.println(entry.getKey());
			System.out.println(entry.getValue());
		}


二、 Map遍历后的结果不会根据put(k,v)的先后,遍历的值顺序是乱的。其实指:
HashMap是无序的,TreeMap的顺序是插入的先后顺序Eg:<span style="color: rgb(85, 85, 85); font-family: 宋体, 'Arial narrow', arial, serif; line-height: 28px;">JAVA 自带的Map</span><span style="color: rgb(85, 85, 85); font-family: 宋体, 'Arial narrow', arial, serif; line-height: 28px;">接口是没有排序功能。即使你按照一定的</span><span style="color: rgb(85, 85, 85); font-family: 宋体, 'Arial narrow', arial, serif; line-height: 28px;">顺序输入,但是输出结果也往往是随机的,对一些特殊的应用很不爽。这时候,可以使用TreeMap类进</span><span style="color: rgb(85, 85, 85); font-family: 宋体, 'Arial narrow', arial, serif; line-height: 28px;">行转换一下就可以了。如果需要排序的功能,最好在new Map对象的时</span><span style="color: rgb(85, 85, 85); font-family: 宋体, 'Arial narrow', arial, serif; line-height: 28px;">候,使用TreeMap. 但是</span><span style="color: rgb(85, 85, 85); font-family: 宋体, 'Arial narrow', arial, serif; line-height: 28px;">如果对已经存在的Map进行按值排序,则需进行转换一下。</span>
eg:<img src="https://img-blog.youkuaiyun.com/20150121170947875?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvenFzNjI3NjExMzA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" style="border: none; max-width: 100%;" />
三、 Map理解
 /*Map集合:存储键值对。要保证键的唯一性。
添加
put(K key,V value)
putAll(Map<? extends K,? extends V> m)
删除
clear()
remove(Object key)
判断
containsValue(Object value)
containsKey(Object key)
isEmpty()
获取
get(Object key)
size()
values()

Map:
Hashtable(JDK1.0)
底层数据结构是哈希表。不可存null键null值。线程同步,效率低。
HashMap(JDK1.2)
底层数据结构是哈希表。允许存入null键null值。不同步,效率高。
TreeMap
底层数据结构是二叉树。线程不同步。可用于给map集合中的键排序。

Map和Set和像,其实Set底层就是使用了Map集合。

map集合的两种取出方式:
1 Set<K> keySet
keySet将所有键取出,存入Set集合,因为Set具备迭代器。
可以用迭代器取出所有键,然后用get方法获取对应值
原理:map集合转成Set集合,再用迭代器取出。
2 Set<Map.Entry<K,V>> entrySet
entrySet将映射关系(Map.Entry类型)取出,存入Set集合,然后用
Map.Entry中的getKey和getValue获取键和值。

其实Entry是Map接口的一个内部接口,即子接口
先有Map集合再有映射关系,是Map集合的内部事务
Map.Entry中存的是映射关系这种数据类型。
内部接口才能加静态修饰符 

四、Map的运用

1、基本概述

Set<Map.Entry<K,V>> entrySet()  返回此映射中包含的映射关系的 set 视图。

Set<K>              keySet()      返回此映射中包含的键的 set 视图。

2、效率分析

对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中,所以就快了。

3、使用举例

Map<String, String> maps = new HashMap<String, String>();   
  //方法一: 用entrySet()   
  Iterator<Entry<String,String>> it = maps.entrySet().iterator();   
  while(it.hasNext()){   
   Map.Entry<String,String> m = it.next();   
   String key = m.getKey();
   String value= m.getValue(); 
  }   
  // 方法二:jdk1.5支持,用entrySet()和For-Each循环()   
  for (Map.Entry<String, String> m : maps.entrySet()) {   
   String key = m.getKey();
   String value= m.getValue();    
  }   
  // 方法三:用keySet()   
  Iterator<String> it2 = maps.keySet().iterator();   
  while (it2.hasNext()){   
   String key = it2.next();
   String value= maps.get(key);
  }   
  // 方法四:jdk1.5支持,用keySet()和For-Each循环   
  for(String m: maps.keySet()){   
   String key = m;
   String value= maps.get(m);
  }

foreach和while的效率几乎是差不多的,而for则相对较慢一些。foreach可以替代掉for吗?显然不是。
foreach的内部原理其实还是 Iterator,但它不能像Iterator一样可以人为的控制,而且也不能调用iterator.remove(),更不能使用下标来方便的访问元素。因此foreach这种循环一般只适合做数组的遍历,提取数据显示等,不适合用于增加删除和使用下标等复杂的操作。


实例:
[java]  view plain copy
  1. //写入值 标签<string name="">value</string>  
  2.     public static boolean saveSearchRecord(Context context,String key,String time){  
  3.         SharedPreferences sp = context.getSharedPreferences("search_record"0);  
  4.         Editor e = sp.edit();  
  5.         //map 映射的总数,大于20条时,末尾插入一条数据  
  6.         int count = sp.getAll().size();  
  7.         if(count <20){  
  8.             e.putString(key, time);  
  9.             //e.putInt("count", count+1);  
  10.         }  
  11.         else{  
  12.             e.putString(key, time);  
  13.             Iterator iter = sp.getAll().entrySet().iterator();  
  14.             int cunIter = 1;  
  15.             Boolean flag =true;  
  16.             while (iter.hasNext()) {  
  17.                 if(cunIter < sp.getAll().size()){  
  18.                     cunIter++;  
  19.                 }else{  
  20.                     //迭代器iter.next(); 返回迭代的下一个对象,  
  21.                     Map.Entry entry = (Map.Entry) iter.next();  
  22.                     Log.v("Boolean"""+iter.hasNext());  
  23.                     Log.v("key", (String) entry.getKey());  
  24.                     if(flag){  
  25.                         e.remove((String) entry.getKey());  
  26.                         flag= false;  
  27.                     }  
  28.                       
  29.                 }     
  30.             }  
  31.                   
  32.         }  
  33.         return e.commit();  
  34.     }  
(2)
[java]  view plain copy
  1. //存HashMap所有值  
  2.     public static void saveHotNewsStatus(Context context,HashMap<String, String> map){  
  3.             SharedPreferences sp = context  
  4.                 .getSharedPreferences("hotnews_status"0);  
  5.             Editor e = sp.edit();  
  6.               
  7.           
  8.             Iterator iter = map.entrySet().iterator();  
  9.               
  10.             while (iter.hasNext()) {  
  11.                 Map.Entry entry = (Map.Entry) iter.next();  
  12.                 String key = (String) entry.getKey();  
  13.                 String val = (String) entry.getValue();  
  14.                   
  15.                 e.putString(key, val);  
  16.             }  
  17.             e.commit();  
  18.             // 效率高,以后一定要使用此种方式!  
  19.     }  

五、 Map 值排序


http://blog.sina.com.cn/s/blog_671565dd010151f8.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值