6

I have a <p:dataTable> where each row has an inputText like this:

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

The items property is a Map<Long, String>:

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

When I submit some data and manually iterate over the map, it apparently works:

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

I get:

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);

then I get a null. Based on the map's contents I should get item1. How is this caused and how can I solve it?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
VCy_A
  • 113
  • 2
  • 4
  • 7
  • 2
    why not just use the p:dataTable var ? – Scary Wombat Nov 12 '13 at 02:11
  • I'm also using p:dataTable var... this var have strings and I can't use it in my Map. I only need to know how can I put the content of the var row inside #value="" or why items.get(1) doesn't work... – VCy_A Nov 12 '13 at 12:31

1 Answers1

6

The 1 which you specified in items.get(1) is specified as an int and autoboxed to Integer. This doesn't equals() a Long value of 1 and hence the key is never found.

Integer int1 = new Integer(1);
Long long1 = new Long(1L);
System.out.println(int1.equals(long1)); // false

You need to specify the 1 as Long instead of (implicitly) as Integer.

String item = items.get(1L);

In case you wonders why you didn't got a compilation error here, it's because Map#get() takes an Object instead of K for the reasons mentioned here: What are the reasons why Map.get(Object key) is not (fully) generic.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Oh! ok. My first option was Map and I continued using an int. Now it works when I specify the 1 as Long. Thanks a lot for your answer. – VCy_A Nov 12 '13 at 14:01