for循环里new对象

今天遇到一个小bug

 

public class Demo extends Base{
public static void main(String[] args) throws ClassNotFoundException {
// InheritedExtend extend = Demo.class.getAnnotation(InheritedExtend.class);
// System.out.println(extend.comment());
// System.out.println(extend.order());
// System.out.println(Demo.class.isAnnotationPresent(InheritedExtend.class));

// Class clazz = Class.forName("annotationTest/person.java");


List<Person> test = new ArrayList<>();

Person person = new Person();

person.name = "我试试";
for (int i = 1;i<10;i++){
test.add(person);
person.name = person.name+i;
}

System.out.println(test.size());

for (Person person1 : test) {
System.out.println(person1.name+" "+"hashcode:" +person1.hashCode());
}

}
}


for循环外面new 对象 for循环里面设置对象的值 然后把对象添加到list里面,实在太抽象了

结果是这样的

 

 



list里面存的是对象的地址,这样子搞list里面的东西全都是一个对象

本意是把对象new在for外面,节省点内存,结果整了个花活

string就可以这样子搞 还有一些包装类之类的可以这样子搞


public class Demo extends Base{
public static void main(String[] args) throws ClassNotFoundException {
// InheritedExtend extend = Demo.class.getAnnotation(InheritedExtend.class);
// System.out.println(extend.comment());
// System.out.println(extend.order());
// System.out.println(Demo.class.isAnnotationPresent(InheritedExtend.class));

// Class clazz = Class.forName("annotationTest/person.java");


List<String> test = new ArrayList<>();

String zifu = "我试试";

for (int i = 1;i<10;i++){
test.add(zifu);
zifu = zifu+i;
}

System.out.println(test.size());

for (String s : test) {
System.out.println(s+" "+"hashcode:"+s.hashCode());
}

}
}

 

string比较特殊  string是不可修改的,你修改完 他直接搞个新的字符串出来 

 

那样子搞,传值的可以用,传地址的不能用

 

posted @   霸王龙168  阅读(816)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2022-01-05 mysql的索引
点击右上角即可分享
微信分享提示