我試圖將一個鍵的值鏈接到另一個鍵的值,但似乎無法讓它作業。
例如,如果我正在創建一個HashMap并向其添加一個鍵值對("x", 0)。然后我希望能夠添加其他鍵映射到與第一個鍵相同的值。
因此,如果我有("x", map.get("y"))并且("y", 0)我希望能夠以某種方式鏈接它。"y"因此,如果我現在像這樣更新鍵的值("y", 10),那么我希望它map.get("x")也應該回傳10。
HashMap<String, Integer> map = new HashMap<>();
map.put("x", 0);
map.put("y", 0);
//I now somehow want to link the value of x so its dependent on y
System.out.println(map.get("x"));
//Should return 0
map.put("y", 10);
System.out.println(map.get("x"));
//Should return 10 now
我不知道如何使它作業,因為 x 總是得到 y 現在的值,而不是 y 在列印值時的值。
uj5u.com熱心網友回復:
如果要將一組鍵與同一個物件關聯起來,可以通過使用可變物件作為值來實作。
例如,您可以使用StringBuilder或實作自定義類。它比實作您自己的地圖的方法更高效、更容易,該地圖擴展并能夠跟蹤這些鍵組并為每次呼叫 或觸發HashMap一系列更新。put()replace()remove()
具有自定義可變的解決方案Container可能如下所示:
HashMap<String, Container<Integer>> map = new HashMap<>();
Container<Integer> commonValue = new Container<>(0);
map.put("x", commonValue);
map.put("y", commonValue);
System.out.println("Value for 'x': " map.get("x"));
System.out.println("Value for 'y': " map.get("y"));
commonValue.setValue(10);
System.out.println("Value for 'x': " map.get("x"));
System.out.println("Value for 'y': " map.get("y"));
Container班級本身。
public class Container<T> {
private T value;
public Container(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}
正如我已經說過的,替代方法是使用 JDK 已經提供的可變類。代碼幾乎相同:
HashMap<String, StringBuilder> map = new HashMap<>();
StringBuilder commonValue = new StringBuilder("0");
map.put("x", commonValue);
map.put("y", commonValue);
System.out.println("Value for 'x': " map.get("x"));
System.out.println("Value for 'y': " map.get("y"));
commonValue.replace(0, commonValue.length(), "10");
System.out.println("Value for 'x': " map.get("x"));
System.out.println("Value for 'y': " map.get("y"));
輸出(兩個版本)
Value for 'x': 0
Value for 'y': 0
Value for 'x': 10
Value for 'y': 10
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432103.html
上一篇:將字典值從$更改為浮點值。蟒蛇硒
