1

This program return null for existing key-value.

Code:

File file = new File("document.xml");
JAXBContext context = JAXBContext.newInstance(Document.class);
Unmarshaller unmarshaller=context.createUnmarshaller();
Document document=(Document)unmarshaller.unmarshal(file);

Map<String, String> map=document.getValues();
System.out.println("Values="+map);
System.out.println(map.get("100300IDG"));

Output:-

  Values={240400MAHAR=100010101, 100300IDG=44444444, 200200MDM=11221321, 341095TRAVERS=7070070, 340203BRUCKNER=545454, 490423SALEM=64845674, 100490MSC=2222222, 240371PRODUCTION=7777777, 250341FASTENAL=121212}

  null

Code for document class.

@XmlRootElement
public class Document {
private Map<String, String> values = new HashMap<String, String>();


//Getter and setter for values


}

Document file that contain values and these values are populated into document object.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<document>
<values>
<entry>
    <key>240400MAHAR</key>
    <value>100010101</value>
</entry>
<entry>
    <key>100300IDG</key>
    <value>44444444</value>
</entry>
<entry>
    <key>200200MDM</key>
    <value>11221321</value>
</entry>
</values>
</document>
4

1 回答 1

4

一种可能性是,打印值Map返回的 Key 对象类似于 但实际上不是实例。因此,将对象与非字符串对象(反之亦然)进行比较并返回,因为找不到。document.getValues()String100300IDGStringmap.get("100300IDG")Stringnull

这一切都取决于如何document.getValues()实施。举个例子

private static Map<String, String> getValues() {
    Map map = new HashMap<>();
    map.put(new MyClass("100300IDG"), "44444444");
    return map;
} 
...
// with  
public class MyClass {
    private String string;

    public MyClass(String string) {
        this.string = string;
    }

    public String toString() {
        return string;
    }
}

它会打印

{100300IDG=44444444}

但实际上不会包含带有 key 的条目"100300IDG"

确保您的密钥类型匹配。编译器在这里不能做太多事情。


或者也许另一个线程删除了打印和获取它之间的条目。

于 2013-11-04T22:13:03.963 回答