繁体   English   中英

Java中是否有基本的id / value对象?

[英]Is there a basic id / value object in Java?

我创建了一个“属性”类,它只是一个键/值单项的包装。 我知道Maps和HashMaps是为此类项目的列表而设计的,因此我感觉自己已经重新发明了轮子……是否有一些Class可以满足此目的?

问候

(我的代码清楚我在寻找什么)

public class Attribut {
    private int id;
    private String value;
    @Override
    public String toString() {
        return value;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

您可以重用Map.Entry<K, V>

http://docs.oracle.com/javase/6/docs/api/java/util/Map.Entry.html

在您的情况下,它将为Map.Entry<Integer, String>

HashMap!

例如:

    Map<Integer,String> attribut = new HashMap<Integer, String>();
    attribut.put(1, "hi");
    String value = attribut.get(1);

您可以迭代:

    for (Integer key : attribut.keySet()) {
        value = attribut.get(key);
    }

编辑:

好,只是一对!

public class Pair<K, V> {

    private final K element0;
    private final V element1;

    public static <K, V> Pair<K, V> createPair(K key, V value) {
        return new Pair<K, V>(key, value);
    }

    public Pair(K element0, V element1) {
        this.element0 = element0;
        this.element1 = element1;
    }

    public K getElement0() {
        return element0;
    }

    public V getElement1() {
        return element1;
    }

}

用法:

    Pair<Integer, String> pair = Pair.createPair(1, "test");
    pair.getElement0();
    pair.getElement1();

一成不变,只有一对!

您不是在“重新发明轮子”,只是在指定您的要求。 您想要一个构成可变的int / String对的类 ,因此您的代码正常。

您的问题是Java语法过于冗长。 最好将其定义为类似

class IdValuePair(id:int,value:String)

但这是其他语言的东西。

您可以使用AbstractMap.SimpleEntry 还有一个SimpleImmutableEntry

但是,我相信设计自己的类型并没有错。 在JDK本身中有很多示例,其中已经完成了类似以下操作(元组):

我相信这是一件好事,因为您的代码更易于阅读,并且获得了额外的类型安全性。

您可以使用[ Collections.singletonMap() ](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#singletonMap(K,V))。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM