Q: A Java collection of value pairs? (tuples?)

D: I like how Java has a Map where you can define the types of each entry in the map, for example . What I'm looking for is a type of collection where each element in the collection is a pair of values. Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time. The collection will maintain its given order and will not treat one of the values as a unique key (as in a map). Essentially I want to be able to define an ARRAY of type or any other 2 types. I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose. I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time. I only need to store pairs in the collection, so I only need two values per entry. Does something like this exist without going the class route? Thanks!

Test Case #10


File ID: #521235-0-cc


   public class Pair {
private final L left;
private final R right;
public Pair(final L left, final R right) {
this.left = left;
this.right = right;
}
public L getLeft() {
return left;
}
public L getLeftOfPair(final Pair pair) {
return pair.getLeft();
}
public R getRight() {
return right;
}
public R getRightOfPair(final Pair pair) {
return pair.getRight();
}
@Override
public int hashCode() {
return left.hashCode() ^ right.hashCode();
}
@Override
public boolean equals(final Object o) {
if (o == null) {
return false;
}
if (!(o instanceof Pair)) {
return false;
}
final Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft())
&& this.right.equals(pairo.getRight());
}
}

  1. Um...no it wouldn't. The fields are marked as final, so they can not be reassigned. And it's not threadsafe because 'left' and 'right' could be mutable. Unless getLeft()/getRight() returned defensive copies (useless in this case), I do not see what the big deal is.
  2. So if I understand correctly, rolling out a simple pair class yields a syntax error, a subpar hashCode method, null pointer exceptions, no compareTo method, design questions ... and people still advocate rolling out this class while it exists in Apache commons. Please, just copy the code if you do not want to include the JAR but stop reinventing the wheel!
  3. What do you mean "easy enough to write on your own""? That's *terrible* software engineering. Are the N^2 adapter classes to convert between MyPair and SomeoneElsesPair also considered easy enough to write on one's own?

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: