[英]Updating elements in an ArrayList in Java?
我有以下课程:
public class Profile{
String name, age, location;
}
说我然后有以下代码:
ArrayList<Profile> profiles = somePopulatedArrayList;
Profile profile = profiles.get(1);
profile.name = "New name here";
我的问题是当我具有以上内容时,是ArrayList中的对象的.name
得到更新,还是我在这里创建一个全新的对象,并且仅更改该对象的.name
,而存储在ArrayList中的Profile
对象仍然具有旧名字?
我正在尝试编辑ArrayList中对象的属性,并且想知道上述方法是否正确?
没有创建新对象。 您已经更新了列表中的对象,也就是说,列表中的对象将以“ New name here”作为名称。
实际上,您可以使用调试器进行测试并查看。
在Java中,所有属于对象类型的变量都包含对对象的引用。 当您调用集合上的get
时,它将返回对该集合内对象的引用,因此,如果您随后继续修改该对象,则其他查看该对象的人都会看到更改。
没有创建新对象,您正在修改现有值。
实际上,这不是一个好习惯,您应该允许直接访问您的类变量,将它们设置为私有变量,并为其提供setter / getter方法。
public class Profile {
private String name, age, location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.