我有下面的類:在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