まず第一に、「自動更新」という用語を忘れましたが、これは次のことを意味します。
int x = 5;
int y = x;
System.out.println(y); //Prints 5
x = 3;
System.out.println(y); //Now prints 3!
(これを参照として使用する人への注意:上記の例は、コメントで対処されているように間違っています。)
ただし、リストでこのアプローチを試しましたが、機能しません。私のコード:
Account.java の関連部分:
public class Account extends Entity<String, Account> {
private String username;
private String password;
public Account(final String username, final String password) {
this.username = username;
this.password = password;
key = username;
data.add(password);
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
}
Entity.java の関連部分:
abstract public class Entity<K, D> {
protected K key;
protected List<Object> data;
public Entity() {
data = new ArrayList<>();
}
public K getKey() {
return key;
}
public List<Object> getData() {
return data;
}
protected List<Object> createData(final DataAction dataAction) {
List<Object> list = new ArrayList<>();
if (dataAction == DataAction.INSERT) {
list.add(key);
}
list.addAll(data);
if (dataAction == DataAction.UPDATE) {
list.add(key);
}
return list;
}
}
たとえば this があるときはいつでもAccount account = new Account("test", "1");
、それを使用するSystem.out.println(account.getData())
と印刷さ[1]
れますが、それでも正しいです。しかし、私が実行するaccount.setPassword("11");
と、その後、期待される代わりにSystem.out.println(account.getData())
まだ出力されます。[1]
[11]
同じメモリの場所を指しているのと同じように、data
自動的に更新されると思っていました。x = y
何が起こっていると思いますか?実装ミス?それとも特徴?また、これを効率的に回避するにはどうすればよいですか?
よろしく。
編集:setPassword()
以下のコードに変更され、動作するようになりました:
public void setPassword(final String password) {
int index = data.indexOf(this.password);
this.password = password;
data.set(index, password);
}
しかし、これに対するより良い解決策はありませんか?3 行のコードが必要になり、そのうちの 2 行は簡単に忘れてしまいます。