1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Richard
  • 5,840
  • 36
  • 123
  • 208
  • 1
    Well where did you expect the `pair` type to come from? Also note that you can't use primitive types in Java generics, which is why `pair` won't work. – Jon Skeet Apr 22 '14 at 14:56
  • That's impossible using just Generics! Congratulations, you hit the Erasure bound.7 – tilpner Apr 22 '14 at 14:56
  • Try to read this question: – ivoruJavaBoy Apr 22 '14 at 14:57
  • 1
    Please don't rely on Vector anymore. This class is from a long time past. Use an ArrayList or similar. – Ray Apr 22 '14 at 14:57
  • It looks an awful lot like you're just translating C++ STL code directly into Java. Java collections are not the same as STL containers, and Java genetics don't work the same as C++ templates, despite the surface similarities. – Laurence Gonsalves Apr 22 '14 at 15:03

4 Answers4

2

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.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
2

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

Community
  • 1
  • 1
schof
  • 43
  • 6
2

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<>();
Kimia
  • 87
  • 1
  • 8
0

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.

dpac697
  • 11
  • 1
  • 3