Question

I want to have a vector of integer pairs in Java so I can store Cartesian coordinates in each cell. So it would look like :

|2,3|4,5|5,6|6,7|

Each cell of the vector has 2 ints. I tried doing this:

Vector<pair<Integer,Integer>> test = new Vector<pair<Integer,Integer>>();

But java could not resolve the word pair (even when I did ctrl+shift+O in eclipse to import all relevant libraries). Then I tried this:

Vector<pair<int,int>> test= new Vector<pair<int,int>>();

But it doesn't like the keyword int for some reason. Any ideas on how to make a vector of int pairs in Java?

Was it helpful?

Solution

I suggest you use e.g. java.awt.Point for this.

It has 2 int coordinates, just what you need.

new Vector<java.awt.Point>

Also, as others noted already, in fact you should use

new ArrayList<java.awt.Point>

and not use Vector.

OTHER TIPS

There is no "pair" in Java. But you can implement it yourself, like suggested here: Creating a list of pairs in java

I had the same problem and since using $ Pair<Integer, Integer> was not a good option for me, I created a small class like

class TestPair{
    int i;
    int j;
}

And then I just normally used the ArrayList

ArrayList<TestPair> testArr = new ArrayList<>();

Min requirement - Java 8 (As till Java 7 Pair class didn't exist).

JavaFX 2.2 has the javafx.util.Pair class which can be used to store a pair.

First import the JavaFX as import javafx.util.Pair;

For example:

Pair p1 = new Pair(1,7); Pair p2 = new Pair(2,6); Pair p3 = new Pair(1,7); System.out.println(p1.equals(p3) + “and” + p2.equals(p3));

OUTPUT : true and false

This way you can use similar methods like getKey() and getValue() etc. Check the doc for more methods and example code snippets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top