不可变对象

Java设计模式之immutable(不可变)模式

点点圈 提交于 2020-03-05 23:04:16
immutable简介 不可变对象永远不会发生改变,其字段的值只在构造函数运行时设置一次,其后就不会再改变 。例如JDK中常见的两种基本数据类型String和Integer,它们都是不可变对象。为了理解immutable与mutable的区别,可以看看下面的一段代码: package date0804.demo2; import java.awt.Point; public class ImmutableString { public static void main(String[] args) { //String,immutable String str = new String("new book"); System.out.println(str); str.replaceAll("new", "old"); System.out.println(str); //Point,mutable Point point = new Point(0,0); System.out.println(point); point.setLocation(1, 0); System.out.println(point); } } 运行结果为 new book new book java.awt.Point[x=0,y=0] java.awt.Point[x=1,y=0]

java中Final关键字和Immutable Class以及Guava的不可变对象

孤街醉人 提交于 2019-12-02 17:09:25
大纲 写这篇文章的起因 java中Final关键字 如何构建不可变对象 Guava中不可变对象和Collections工具类的unmodifiableSet/List/Map/etc的区别 实验代码 写这篇文章的起因 java项目在使用FindBugs扫描的时候报了一个不能使用可变对象,记得报的是类似如下的信息: MS: Field is a mutable collection (MS_MUTABLE_COLLECTION) 官方解释: A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. Consider wrapping this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability. 参考FindBugs的描述:http://findbugs.sourceforge.net/bugDescriptions.html 由于最近学习的东西较多,对有些基本的概念略有生疏,所以又温故了一下,顺便提供下上面问题的解决方案,仅供参考。