Java – How to store Array of pairs

In this article you can see a sample code I use to store simple Key-Value pairs in another objects, i.e. List or ArrayList

public class Pair<Key,Value> {
    private Key key;
    private Value value;

    public Pair(Key key, Value value){
        this.key = key;
        this.value = value;
    }

    public Key getKey(){ return this.key; }
    public Value getValue(){ return this.value; }

    public void setKey(Key key){ this.key = key; }
    public void setValue(Value value){ this.value = value; }
}

Then instantiate a variable of type i.e. List<> using the following command

List<Pair<Integer,String>> pairList = new ArrayList<Pair<Integer,String>>();

Leave a Reply