由于服务代码逻辑需要在map中的value存储Boolean,后面的代码逻辑 中我想更改Boolean的值发现更改不了,后来查找资料才发现原来Boolean实现类是定义为final,还是对原理不了解呀,以后多注重原理。
测试代码(final类):
HashMap<String,Boolean> map = new HashMap<String, Boolean>();map.put("1", false);map.put("2", true);map.put("3", false);Collection<Boolean> values = map.values();for (Boolean v : values) {v = Boolean.valueOf(true);}Collection<Boolean> vs = map.values();System.out.println(vs);
结果:[false, true, false]
发现值依旧没有发生改变
测试代码(自定义类):
HashMap<Integer,News> map = new HashMap<Integer, News>();map.put(1, new News(1, "weijie"));map.put(2, new News(2, "hexiang"));Collection<News> values = map.values();for (News news : values) {news.id = 5;}Collection<News> values2 = map.values();for (News news : values2) {System.out.println(news);}
结果: News [id=5, name=weijie]
News [id=5, name=hexiang]
自定义的类不是final类型因此对象内容通过引用后的变量可以对地址空间的内容进行修改。
参考博客:Boolean 源码