想要创建一个也可以嵌套对的keyvalue

时间:2011-12-09 22:41:12

标签: java

我的xml看起来像:

<node key="asdfasdf">value</node>

但也可能像:

<node key="asdf">
  <node key="2234">asdfsdf</node>
  <node key="223422"> qasdfljk</node>
</node>

99%的时间没有嵌套的键/值对,那么我应该如何创建keyvalue类? 我想我应该懒得初始化内部集合?

我应该如何定义这个类,我应该继承SimpleEntry吗?

2 个答案:

答案 0 :(得分:3)

我不知道这是不是一个好主意:

public class Node {
    private String key;
    private String value;
    private List<Node> subNodes;

    //you can check if the node has subnode(s)
    private boolean hasSubNodes(){
        return !(subNodes == null || subNodes.isEmpty());
    }

    // if there is nested node, cannot call getValue 
    private String getValue(){
        if (hasSubNodes())
            throw new RuntimeException("blahblah");
        else
            return value;
    }

    //getters,setters are omitted

}

通过这种方式,您可以拥有任意数量的嵌套。

答案 1 :(得分:1)

您可以使用Guava Multimap,这些集合代表您所需要的。 http://code.google.com/p/guava-libraries/

示例:

public static void main(final String[] args) throws Exception {

    final Multimap<String, Entry<String, String>> multimap = HashMultimap.create();
    multimap.put("asdfasdf", new NodeEntry(null, "value"));
    multimap.put("asdf", new NodeEntry("2234", "asdfsdf"));
    multimap.put("asdf", new NodeEntry("223422", "qasdfljk"));

    System.out.println(multimap);

}

class NodeEntry implements Entry<String, String> {

    private final String key;
    private final String value;

    public NodeEntry(final String key, final String value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public String getKey() {
        return key;
    }

    @Override
    public String getValue() {
        return value;
    }

    @Override
    public String setValue(final String value) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("NodeEntry [key=").append(key).append(", value=").append(value).append("]");
        return builder.toString();
    }

}