Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a basic id / value object in Java?

Tags:

java

I've created an "Attribut" class which is just a wrapper for a key/value single item. I know that Maps and HashMaps are designed for lists of this kind of items so I feel like i reinvented the wheel... Is there some Class which fulfill this purpose ?

Regards

( My code to be clear about what i'm looking for )

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;
    }
}
like image 358
chamel Avatar asked Feb 18 '26 15:02

chamel


2 Answers

You can reuse Map.Entry<K, V>:

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

In your case it'd be Map.Entry<Integer, String>.

like image 102
duffymo Avatar answered Feb 20 '26 05:02

duffymo


HashMap !

example :

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

you can iterate :

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

EDIT :

OK, just for a Pair !

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;
    }

}

usage :

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

Immutable, only a pair !

like image 21
Bastiflew Avatar answered Feb 20 '26 03:02

Bastiflew