今天在测试的时候偶然发现一个问题:new一个HashMap静态变量当作模版使用。就想java里面的对象引用都是值引用,就算用别的变量去引用它进行一些修改也不会对模版有任何影响。然而事实却是它把我的模版也给改了?!!
就如下面一段代码
private static Map<String,String> orderReportForm=new HashMap<>(3);
@Test
public void test3() {
Map<String,String> msg=DemoTest.orderReportForm;
msg.put("test", "test");
System.out.println("static:"+DemoTest.orderReportForm);
System.out.println("test3:"+msg);
}
打印的结果:
static:{test=test}
test3:{test=test}
对比一下String类型的静态变量
private static String msg="DemoTest";
@Test
public void test3() {
String m=DemoTest.msg;
m="test3";
System.out.println("static:"+DemoTest.msg);
System.out.println("test3:"+m);
}
打印的结果:
static:DemoTest
test3:test3
可能我基础学的也不太好吧,都是自学的,这是什么情况???
好吧。是我糊涂了,太久没复习基础都丢人了#_#
java里基本类型是值引用,而对象都是地址引用的。
先看看String的图解
如图,打印的结果也就一目了然了吧,msg是始终指向DemoTest的;
再看看Map的图解
如图,两个对象都是指向同一个map,而代码改变的是map里面存储的值
所以打印的结果却是改变了orderReportForm的情况。
另外解决方法也是比较简单
private static Map<String,String> orderReportForm=new HashMap<>(3);
@Test
public void test3() {
//强制让它new一个新对象
Map<String,String> msg=new HashMap<>(DemoTest.orderReportForm);
msg.put("test", "test");
System.out.println("static:"+DemoTest.orderReportForm);
System.out.println("test3:"+msg);
}
打印的结果:
static:{}
test3:{test=test}