Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can’t get value of Map<Long, String> by key

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?

like image 749
VCy_A Avatar asked Nov 12 '13 02:11

VCy_A


People also ask

How do I get the value of a map for a specific key?

util. HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Can we use string as key in map?

String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.

How do you find the value of string on a map?

For this, just declare HashMap as HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); Using this will make your code cleaner and also you don't have to convert the result of hs. get("my_code") to string as by default it returns value of string if at entry time one has kept value as a string.

Can you get a HashMap key with a value?

Get keys from value in HashMap To find all the keys that map to a certain value, we can loop the entrySet() and Objects. equals to compare the value and get the key. The common mistake is use the entry. getValue().


1 Answers

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.

like image 63
BalusC Avatar answered Oct 07 '22 11:10

BalusC