`
Donald_Draper
  • 浏览: 950974 次
社区版块
存档分类
最新评论

深入理解Collections的unmodifiableMap(Map map)方法

    博客分类:
  • JAVA
阅读更多
深刻理解IdentityHashMap:http://donald-draper.iteye.com/blog/2326264
方法说明:
public static<K,V> Map<K,V> unmodifiableMap(Map<?extendsK,?extendsV>m)
返回指定映射的不可修改视图。此方法允许模块为用户提供对内部映射的“只读”访问。
在返回的映射上执行的查询操作将“读完”指定的映射。试图修改返回的映射
(不管是直接修改还是通过其collection视图进行修改)将导致抛出UnsupportedOperationException。
如果指定映射是可序列化的,则返回的映射也将是可序列化的。
参数:
m-将为其返回一个不可修改视图的映射。
返回:
指定映射的不可修改视图。
测试:
package test;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;

public class TestMap  {
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) {
		Map mp = new HashMap<String, String>();
		mp.put("1", "s");
		mp.put("2", "t");
		/*Collection ct = mp.values();
		System.out.println(ct.toString());*/
		mp.put("1", "t");
		Set<Map.Entry<String, String>> allSet = mp.entrySet();
		Iterator<Map.Entry<String, String>> iter = allSet.iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> me = iter.next();
			System.out.println(me.getKey() + " --> " + me.getValue());
		}
		//HashMap
		Map mpx = new HashMap<Cat, String>();
		mpx.put(new Cat("kitty",1), "kitty_1");
		mpx.put(new Cat("jime",2), "jime_2");
		mpx.put(new Cat("kitty",1), "kitty_2");
		Set<Map.Entry<Cat, String>> allSetx = mpx.entrySet();
		Iterator<Map.Entry<Cat, String>> iterx = allSetx.iterator();
		while (iterx.hasNext()) {
			Map.Entry<Cat, String> me = iterx.next();
			System.out.println(me.getKey() + " --> " + me.getValue());
		}
		System.out.println("==============IdentityHashMap:");
		//IdentityHashMap
		Map imp = new IdentityHashMap<Cat, String>();
		Cat cat = new Cat("kitty",1);
		imp.put(cat, "kitty_1");
		imp.put(new Cat("jime",2), "jime_2");
		imp.put(new Cat("kitty",1), "kitty_2");
		Set<Map.Entry<Cat, String>> iSet = imp.entrySet();
		Iterator<Map.Entry<Cat, String>> iterxx = iSet.iterator();
		while (iterxx.hasNext()) {
			Map.Entry<Cat, String> me = iterxx.next();
			System.out.println(me.getKey() + " --> " + me.getValue());
		}
		System.out.println("==============unmodifiableMap:");
		//test Collections.unmodifiableMap();
		Map impx =  Collections.unmodifiableMap(imp);
		cat.setName("baibi");
		Set<Map.Entry<Cat, String>> uSet = impx.entrySet();
		Iterator<Map.Entry<Cat, String>> iterU = uSet.iterator();
		while (iterU.hasNext()) {
			Map.Entry<Cat, String> me = iterU.next();
			System.out.println(me.getKey() + " --> " + me.getValue());
		}
		impx.put(new Cat("Luyies",6), "Luyies_6");
	}
}

控制台输出:
2 --> t
1 --> t
姓名:jime,年龄:2 --> jime_2
姓名:kitty,年龄:1 --> kitty_2
==============IdentityHashMap:
姓名:kitty,年龄:1 --> kitty_2
姓名:jime,年龄:2 --> jime_2
姓名:kitty,年龄:1 --> kitty_1
==============unmodifiableMap:
姓名:kitty,年龄:1 --> kitty_2
姓名:jime,年龄:2 --> jime_2
姓名:baibi,年龄:1 --> kitty_1
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Unknown Source)
at test.TestMap.main(TestMap.java:63)
我们来查看一下Collections的方法:
public class Collections
{
    public static Map unmodifiableMap(Map map)
    {
        return new UnmodifiableMap(map);
    }

    public static SortedMap unmodifiableSortedMap(SortedMap sortedmap)
    {
        return new UnmodifiableSortedMap(sortedmap);
    }
//UnmodifiableMap为Collections的静态内部类
private static class UnmodifiableMap
        implements Map, Serializable
    {
        static class UnmodifiableEntrySet extends UnmodifiableSet
        {
            private static class UnmodifiableEntry
                implements Map.Entry
            {

                public Object getKey()
                {
                    return e.getKey();
                }

                public Object getValue()
                {
                    return e.getValue();
                }

                public Object setValue(Object obj)
                {
                    throw new UnsupportedOperationException();
                }

                public int hashCode()
                {
                    return e.hashCode();
                }

                public boolean equals(Object obj)
                {
                    if(this == obj)
                        return true;
                    if(!(obj instanceof Map.Entry))
                    {
                        return false;
                    } else
                    {
                        Map.Entry entry = (Map.Entry)obj;
                        return Collections.eq(e.getKey(), entry.getKey()) && Collections.eq(e.getValue(), entry.getValue());
                    }
                }

                public String toString()
                {
                    return e.toString();
                }

                private Map.Entry e;

                UnmodifiableEntry(Map.Entry entry)
                {
                    e = entry;
                }
            }


            public Iterator iterator()
            {
                return new Iterator() {

                    public boolean hasNext()
                    {
                        return i.hasNext();
                    }

                    public Map.Entry next()
                    {
                        return new UnmodifiableEntry((Map.Entry)i.next());
                    }

                    public void remove()
                    {
                        throw new UnsupportedOperationException();
                    }

                    public volatile Object next()
                    {
                        return next();
                    }

                    private final Iterator i;
                    final UnmodifiableEntrySet this$0;

                   
                    {
                        this$0 = UnmodifiableEntrySet.this;
                        super();
                        i = c.iterator();
                    }
                };
            }
            private static final long serialVersionUID = 7854390611657943733L;

            UnmodifiableEntrySet(Set set)
            {
                super(set);
            }
        }

        public Set keySet()
        {
            if(keySet == null)
                keySet = Collections.unmodifiableSet(m.keySet());
            return keySet;
        }

        public Set entrySet()
        {
            if(entrySet == null)
                entrySet = new UnmodifiableEntrySet(m.entrySet());
            return entrySet;
        }
        private static final long serialVersionUID = -1034234728574286014L;
        private final Map m;
        private transient Set keySet;
        private transient Set entrySet;
        private transient Collection values;
        UnmodifiableMap(Map map)
        {
            keySet = null;
            entrySet = null;
            values = null;
            if(map == null)
            {
                throw new NullPointerException();
            } else
            {
                m = map;
                return;
            }
        }
    }
}
从上我们看一看出UnmodifiableMap不知处put,remove操作。
总结:
实现原是是包装了下map不支持改变大小的操作 ,仅仅返回的Map不能putremove操作, 但可以对里的对象进行操

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics