How to store an array of pairs in Java?

Create your own class to represent a pair and add a constructor that takes two arguments:

public class MyPair
{
    private final Double key;
    private final Double value;

    public MyPair(Double aKey, Double aValue)
    {
        key   = aKey;
        value = aValue;
    }

    public Double key()   { return key; }
    public Double value() { return value; }
}

See this answer for reasons why a Pair does not exist in Java: What is the equivalent of the C++ Pair<L,R> in Java?


You don't want to use Entry it's an INTERFACE, not a CLASS. That interface is used by an implementations of Set when you call entrySet() on a class that implements Map. It basically lets you manipulate the implemented Map as though it were a Set.

What you would do (but can't) is this. If you try to do this you'll see a compiler error along the lines of "Cannot instantiate the type Map.Entry". That's because Map.Entry is an interface, not a class. An interface doesn't contain any real code, so there's no real constructor to run here.

Entry<Double, Double> pair = new Entry<Double, Double>();

If you look at the below docs you can clearly see at the top that it's a "Interface Map.Entry" which means it's an interface. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Map.Entry.html

What you should do instead of trying to instantiate an interface, which is impossible, is create your own class called Pair. Something like this. Remember to change the package if you use the below code.

package org.mike.test;

public class Pair {
    private double x = 0.0;
    private double y = 0.0;

    public Pair(double x, double y)
    {
        this.x = x;
        this.y = y;
    }

    public Pair()
    {

    }

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }


}

After writing your Pair class your code will now look like this.

package org.mike.test;

import java.util.ArrayList;
import org.mike.test.Pair; //You don't need this if the Pair class is in the same package as the class using it

public class tester {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ArrayList<Pair> values = new ArrayList<Pair>();
        Pair pair = new Pair();
        // set pair values:
        pair.setY(3.6);
        pair.setX(3.6);
        values.add(pair);
    }

}

Tags:

Java

Arrays