我有一个 <p:dataTable>
每行都有一个这样的输入文本:
<p:dataTable ... rowIndexVar="row">
<p:column>
<p:inputText value="#{myBean.items[row + 1]}" />
</p:column>
</p:dataTable>
items
属性是 Map<Long, String>
:
private Map<Long, String> items = new HashMap<Long, String>();
当我提交一些数据并手动遍历 map 时,它显然有效:
Iterator itr = items.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry) itr.next();
System.out.println("key: " + e.getKey() + " " + "value: " + e.getValue());
}
我得到:
key: 1 value: item1 key: 2 value: item2 key: 3 value: item3 key: 4 value: item4
However, when I try to get a specific item by key
String item = items.get(1);
然后我得到一个 null
.根据 map 的内容,我应该得到 item1
.这是怎么引起的,我该如何解决?
最佳答案
您在 items.get(1)
中指定的 1
被指定为 int
并自动装箱为 Integer
。这不是 equals()
Long
值 1
,因此永远找不到 key 。
Integer int1 = new Integer(1);
Long long1 = new Long(1L);
System.out.println(int1.equals(long1)); // false
您需要将 1
指定为 Long
而不是(隐式地)指定为 Integer
。
String item = items.get(1L);
如果您想知道为什么这里没有出现编译错误,那是因为 Map#get()
由于此处提到的原因,采用 Object
而不是 K
:What are the reasons why Map.get(Object key) is not (fully) generic .
关于java - 无法通过键获取 Map<Long, String> 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19919627/