-2

我有一个已经填充的哈希图。我将 abc123 映射到 123。

我首先声明一个名为 test 的对象并给它一个 abc123 的值

然后我检查我的 hashmap 是否包含 abc123。

如果为真,它将进​​入 if 语句并获取 abc123 的映射并将其放入一个名为 value 的字符串中

然后我想用 123 替换 abc123

现在我的 hashmap 键是 123,我的值是 123

我将如何摆脱 123 的价值

我希望能够打印出到 123 的映射并获得 null

public void replace1(Map<String, String> barcodeMap) {
  Object test = "abc123";

  if (barcodeMap.containsKey(test)) {

     System.out.println("HERE I WILL PRINT THE MAPPING OF AGILENT         " + barcodeMap.get(test)); //output here is 123

     String value = barcodeMap.get(test);

     System.out.println("THE MAPPING OF VALUE SHOULD BE NULL     " + barcodeMap.get(value)); //output here is null

     barcodeMap.put(value, barcodeMap.remove(test));

     System.out.println("HERE I WILL PRINT THE MAPPING OF AGILENT it should be null:::::   " + barcodeMap.get(test)); //output here is null

     System.out.println("HERE IS THE MAPPING OF VALUE::::::::::::::       " + barcodeMap.get(value)); //output here is 123, i want it to be null here

  }

}

4

3 回答 3

2

使用该remove方法从 a 中删除键/值对Map(请参阅链接的文档)。

barcodeMap.remove(value);

...我仍然不清楚你为什么要做你正在做的任何事情,因为你正在添加一个你显然不想要的键/值对Map


如果您希望密钥保留但具有null其值,那就更简单了——只需将密钥添加到您真正想要的值即可。现在都在一条线上:

barcodeMap.put(barcodeMap.remove(test), null);

这会将 的结果barcodeMap.remove(test)作为键添加到barcodeMap,其值为null

于 2013-09-24T14:08:40.383 回答
2

而是barcodeMap.put(value, barcodeMap.removre(test));使用

barcodeMap.remove(test); barcodeMap.put(value, null);

于 2013-09-24T14:16:32.637 回答
1

检查 HashMap 的 JavaDoc。

有一个 remove() 方法。

于 2013-09-24T14:08:47.757 回答