【问题标题】:Can’t get value of Map<Long, String> by key无法按键获取 Map<Long, String> 的值
【发布时间】:2013-11-24 00:55:06
【问题描述】:

我有一个&lt;p:dataTable&gt;,其中每一行都有一个这样的 inputText:

<p:dataTable ... rowIndexVar="row">
    <p:column>
        <p:inputText value="#{myBean.items[row + 1]}" />
    </p:column>
</p:dataTable>

items 属性是 Map&lt;Long, String&gt;

private Map<Long, String> items = new HashMap<Long, String>();

当我提交一些数据并手动迭代地图时,它显然有效:

Iterator itr = items.entrySet().iterator();
while (itr.hasNext()) {
    Map.Entry e = (Map.Entry) itr.next();
    System.out.println("key: " + e.getKey() + " " + "value: " + e.getValue());
}

我明白了:

键:1 值:item1 键:2 值:item2 键:3 值:item3 键:4 值:item4

但是,当我尝试按键获取特定项目时

String item = items.get(1);

然后我得到一个null。根据地图的内容,我应该得到item1。这是如何引起的,我该如何解决?

【问题讨论】:

  • 为什么不直接使用 p:dataTable 变量?
  • 我也在使用 p:dataTable var...这个 var 有字符串,我不能在我的地图中使用它。我只需要知道如何将 var 行的内容放入 #value="" 或为什么 items.get(1) 不起作用...

标签: java jsf-2 primefaces hashmap el


【解决方案1】:

您在items.get(1) 中指定的1 被指定为int 并自动装箱为Integer。这不是equals()Long1,因此永远找不到密钥。

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

【讨论】:

  • 哦!好的。我的第一个选择是 Map,我继续使用 int。现在,当我将 1 指定为 Long 时它可以工作。非常感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 2021-11-29
相关资源
最近更新 更多