我有下面的类:在Java中更新ArrayList中的元素?
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中的对象的属性,我想知道上述方法是否正确?
以这种方式访问类字段不是一个好习惯。您应该将它们声明为私有字段,并使用getter/setter。 –
profiles.get(1).setName('newName'); –
ArrayList中没有'对象',这就是你需要从这个问题中学习的东西。该列表包含指向内存中某个对象的引用(地址)。 – Fernando