gpt4 book ai didi

java - Hashmap 接收 true 而不是 ArrayList

转载 作者:行者123 更新时间:2023-12-01 18:25:36 25 4
gpt4 key购买 nike

事实证明,我正在工作(如您所见,我还不是高级开发人员),但突然我意识到我的代码出了问题。 Hashmap 接收“true”,而不是接收第一个位置有一个对象的 ArrayList。举个例子,你可以看到我在说什么:

    Product item = new Product(); 
Map rMap = new HashMap();
rMap.put("productsList", new ArrayList().add(item));

在某些代码行和编码 helperMethods 之后,我尝试从 map 中检索“productsList”,但我无法这样做,我不知道为什么,所以在调试之后我发现当 PUT 完成时,没有这样的列表,只是一个 boolean 值。我检索的方式如下:

       if (rMap.containsKey("productsList")) {
// This IF statement was being skipped because of the Boolean
if (rMap.get("productsList") instanceof ArrayList) {
List<Product> pr = (List) rMap.get("productsList");
}
}

另一方面,我已经得到了这个(这更清楚)并且按预期工作:

    Product item = new Product();
Map rMap = new HashMap();
List < Product > myList = new ArrayList();
myList.add(item);

rMap.put("productsList", myList);

如何才能减少创建列表并将对象设置到列表的这两行代码?当然这没什么大不了的,只是我想让我的编码更清晰、更直接。

最佳答案

您可以使用Arrays#asList像这样的方法

map.put("productList", Arrays.asList(item1, item2, item3));

此外,我建议您使用泛型,作为交换,您将获得类型安全。

Map<String, List<String>> rMap = new HashMap<String, List<String>>();
rMapu.put("productList", Arrays.asList("item1", "item2"));

关于java - Hashmap 接收 true 而不是 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26330779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com