java - 无法通过键获取 Map<Long, String> 的值

标签 java jsf-2 primefaces hashmap el

我有一个 <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() Long1,因此永远找不到 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/

相关文章:

java - JSF:如何向支持 bean 中的组件添加 ajax 功能?

jsf-2 - 对话框内的 Primefaces commandButton 不触发支持 bean 的方法

file-upload - 如何使用 JSF/Primefaces 上传文件?

css - <p :datatable> without borders and column headers

java - Primefaces ajax 不工作

java - Spring Autowiring 提供 NPE。不手动创建bean

java - 似乎 Set-Cookie 的过期格式为 Mon, 25 Sep 2017 13 :40:02 GMT could not be parsed my apache http client

java - MongoDB 聚合到 Java

java - 在 primefaces 数据表中选择行

java - 通过套接字跨网络传输 float