博主自身只是一枚刚入编程坑的菜鸟,此文记录的问题较为肤浅,仅供小小白学习
先来看一段demo代码及结果:
1 package test; 2 3 import java.util.ArrayList; 4 5 public class Demo { 6 7 public static void main(String[] args) { 8 ArrayList<Person> personList = new ArrayList<Person>(); 9 //方法一: 10 for(int i = 0; i < 5 ; i++){ 11 Person person = new Person("person " + i , 20 + i); 12 personList.add(person); 13 } 14 for (Person people : personList) 15 System.out.println(people.getName() + " ... " + people.getAge()); 16 17 System.out.println("-------------华丽的分割线----------"); 18 personList.clear(); 19 20 //方法二: 21 Person person = new Person(); 22 for(int i = 0; i < 5 ; i++){ 23 person.setName("person " + i); 24 person.setAge(20 + i); 25 personList.add(person); 26 } 27 for (Person people : personList) 28 System.out.println(people.getName() + " ... " + people.getAge()); 29 30 31 } 32 } 33 34 class Person { 35 private String name; 36 private int age; 37 38 Person(){} 39 40 Person(String name, int age) { 41 this.name = name; 42 this.age = age; 43 } 44 45 public String getName() { 46 return name; 47 } 48 49 public void setName(String name) { 50 this.name = name; 51 } 52 53 public int getAge() { 54 return age; 55 } 56 57 public void setAge(int age) { 58 this.age = age; 59 } 60 61 }
结果:
person 0 ... 20 person 1 ... 21 person 2 ... 22 person 3 ... 23 person 4 ... 24 -------------华丽的分割线---------- person 4 ... 24 person 4 ... 24 person 4 ... 24 person 4 ... 24 person 4 ... 24
原因分析:
方法一将引用变量定义在循环内部,每次循环都会在内存中开辟一个空间用于存放该引用变量,5次循环后内存中有5个引用变量,list集合中的5个引用分别指向了这5个变量
方法二将引用变量定义在循环外部,每次循环都只是给该变量进行重新赋值,并不会重新开辟空间存放变量,5次循环后内存中仍只有1个引用变量,list集合中的5个引用均指向了这个变量
时间: 2024-11-08 21:12:15