chamel
chamel

Reputation: 367

Is there a basic id / value object in 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;
    }
}

Upvotes: 3

Views: 3074

Answers (5)

scravy
scravy

Reputation: 12283

You can use AbstractMap.SimpleEntry. There is also a SimpleImmutableEntry.

However, I believe that it is not wrong designing your own type. There is a plethora of examples in the JDK itself where something like this (tuple) has been done:

I believe that it's a good thing, since you're code is more easily readable and you gain additional type safety.

Upvotes: 1

Bastiflew
Bastiflew

Reputation: 1166

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 !

Upvotes: 2

Ingo Kegel
Ingo Kegel

Reputation: 48070

You're not "reinventing the wheel", you just specifying your requirements. You want a class that constitutes a mutable int/String pair, and so your code is OK.

Your problem is that Java syntax is overly verbose. It would be nice to simply define it as something like

class IdValuePair(id: int, value: String)

but that's something for other languages.

Upvotes: 1

duffymo
duffymo

Reputation: 308938

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>.

Upvotes: 2

Crozin
Crozin

Reputation: 44386

You could use [Collections.singletonMap()](http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#singletonMap(K, V)).

Upvotes: 0

Related Questions