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 @ 2023-01-05 17:10  霸王龙168  阅读(840)  评论(0)    收藏  举报