HashMap with single character keys from Java

45 views (last 30 days)
I'm attempting to read in values from a HashMap created in Java. For some reason, when I try to retrieve a value with a single character key (i.e. "X"), I get an empty value back, like it didn't find the key.
Code in Java to create HashMap:
public Map<String, Object> getFakeHashMap() {
LinkedHashMap<String, Object> map = new LinkedHashMap();
map.put("X", (double)0.01);
return map;
}
If I get a quick look at what is returned to matlab when I get the entire hashMap:
>> test = javaobj.getFakeHashMap
test =
{X=0.01}
It appears that the value has made it to MATLAB. but, if I try to actually retreive it
val = test.get('X')
val =
[]
Empty set...bubkus... Any multi character key seems to work fine. Replace "X" with "PX" and it works great.
Does anyone know what may be causing this? I really want to keep my naming as it is, since this is set by a naming convention that has to be used across my applications.

Answers (1)

Florian Schwaiger
Florian Schwaiger on 3 Feb 2015
Old thread but found the solution, have the same problem using snakeyaml parser.
Matlab converts the keys to native char sequences when reading from Java. When passing them to Java again, they get automatically boxed. For Matlab 1x1 char, the corresponding Java object is a native "char" too. For Matlab 1xn char arrays, the boxed object is "java.lang.String".
Maps require "java.lang.String" as keys, passing "char" returns []. Wrap the key explicitly in a String constructor, like so:
map.get(java.lang.String(key));

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!