2011-05-22 69 views
1

我有一個地圖對象testMap聲明爲HashMap<String, Test>如何更新值的一個在地圖

測試是一個簡單的類,它包含一個Object和兩個String值引用。

public class Test { 

    private String name; 
    private String id; 
    private Object val; 


public Test(Object val,String name.String id){ 
    this.val =val; 
    this.id=id; 
    this.name = name; 
} 

我想只有在哈希表更新「名稱」「testMap。」我怎樣才能做到這一點?

+0

「name」是否指測試實例存儲在testMap中的字符串鍵?即 - 如果我沒有'testMap.put( 「的myKey」,新的測試(鄰, 「STR1」, 「STR2」);',你說你要更改的' 「的myKey」'價值 – 2011-05-22 08:51:13

回答

0

您需要將name財產的可視性更改爲public或二傳手添加到它:

public class Test { 

    private String name; 
    private String id; 
    private Object val; 


public Test(Object val,String name, String id){ 
    this.val =val; 
    this.id = id; 
    this.name = name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

然後,改變你的名字,你需要

Test test = testMap.get("key"); 
if (test != null) { 
    test.setName("new name"); 
} 

如果你也想更新地圖的關鍵,那麼你需要

Test test = testMap.remove("oldKey"); 
if (test != null) { 
    test.setName("newKey"); 
    test.put("newKey", test); 
} 
+2

我想知道downvote的原因 – 2011-05-22 09:13:55

1
Test test = testMap.get("key"); 
if (test != null) { 
    test.name = "new name"; 
} 
+0

另外,?這個工作,你應該做'Test'類'public',而不是'private'的'name'成員 – 2011-05-22 08:35:11

+0

我想在HashMap來更新名稱 – ssbecse 2011-05-22 08:36:07

+0

附記:。它會改變測試的情況下,因此,任何其他參考也會看到新的值。 – Howard 2011-05-22 08:36:36

0
Test test = testMap.remove("name"); 
if(test != null) 
    test.put("newname",test); 
0

由於名稱是私有字段,因此您不能使用當前實現的Test。你可以把它公開或者增加getter/setter方法到Test類(目前Test類看起來完全沒用,除非你沒有遺漏一些代碼)。

之後,你可以用一個新的必要的領域取代Test所需的實例,或更新名稱。代碼:

public class Test { 
    public String name; 
    public String id; 
    public Object val; 

    public Test(Object val,String name.String id){ 
    this.val =val; 
    this.id=id; 
    this.name = name; 
    } 
} 

Map<String, Test> testMap = new HashMap<String, Test(); 
... 
Test test = testMap.get(key); 
test.name = newName; 
testMap.put(key, test); 

// or 
Test test2 = testMap.get(key); 
testMap.put(key, new Test(test2.val, newName, test2.id));