开发者

HashMap.containsKey(Object key) can't find a key

Sure I do something wrong, but can't realize what :) I populate a key/value pair collection Map keyValuePairs with data, after I try to check collection for specific key existence in a common way keyValuePairs.containsKey("Name") and get back "false". But keyValuePairs.keySet() gives back set of keys where "Name" exists.

public static void parseBusinessObject(Str开发者_Go百科ing input, Object output) {

Class parsingObject = output.getClass();
Field[] fields = parsingObject.getDeclaredFields();

Pattern pattern = Pattern.compile("([^{=;]*)=([^;}]*);");
Matcher matcher = pattern.matcher(/*input*/"anyType{Id=1; Name=Til afskrivning; LocationId=1; Editable=true; Default=true; Transcribed=false; }");
Map<String, String> keyValuePairs = new HashMap<String, String>();
while (matcher.find()) {
    if(!keyValuePairs.containsKey(matcher.group(1))){
    keyValuePairs.put(matcher.group(1).trim(), matcher.group(2).trim());
}
}

for (Field field : fields) {
    if(keyValuePairs.containsKey(field.getName())){
        //TODO: add values to fields    
    }
}
}

output result after matching:

 Id=1;
 Name=Til afskrivning;
 LocationId=1;
 Editable=true;
 Default=true;
 Transcribed=false;

"keyValuePairs"= HashMap (id=830062742672) { LocationId=1, Default=true, Editable=true, Name=Til afskrivning, Id=1, Transcribed=false}

"keyValuePairs.keySet()"= HashMap$1 (id=830062763448)

[ LocationId, Default, Editable, Name, Id, Transcribed]

"keyValuePairs.containsKey("Name")"= false

Could anybody please explain me what's wrong with it? Thank you.


Quoting the information you gave in the question:

"keyValuePairs.keySet()"= HashMap$1  (id=830062763448)  
[ LocationId,  Default,  Editable,  Name, Id,  Transcribed]

The extra spaces in front of some of the key names suggest that the key inserted was " Name" (note the preceding space). If you give more information about the regex, we may be able to figure out why this happened.

You can also debug this yourself by logging/printing what group(1) and group(2) matches; I'm sure you'll find that it matches the extra whitespaces.

A quick fix is to put group(1).trim() and group(2).trim() into the map instead, but the better option is to fix the regex.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜