第4条:避免创建重复的对象

来源:互联网 发布:java文件上传到数据库 编辑:程序博客网 时间:2024/06/05 08:16
String s = new String("silly");


上面的代码,会创建一个新的String实例,每次都是新的内存地址,应该改为:

String s = "silly";

测试如下:

String s1 = new String("silly");String s2 = new String("silly");System.out.println(s1 == s2);String s3 = "silly";String s4 = "silly";System.out.println(s3 == s4);


测试结果:

falsetrue


因为new会分配内存。如果对象是不可变的,那么应该重用这个对象。

原创粉丝点击