Back

Explore Courses Blog Tutorials Interview Questions
0 votes
5 views
in Java by (4k points)
I like how Java has a Map where you can define the types of each entry in the map, for example <String, Integer>.

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 <String,Integer> 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!

1 Answer

0 votes
by (46k points)

The Pair class is one of these "gimme" generics models that is clear enough to write on your own. For instance, off the top of my head:

public class Pair<L,R> {

  private final L left;

  private final R right;

  public Pair(L left, R right) {

    this.left = left;

    this.right = right;

  }

  public L getLeft() { return left; }

  public R getRight() { return right; }

  @Override

  public int hashCode() { return left.hashCode() ^ right.hashCode(); }

  @Override

  public boolean equals(Object o) {

    if (!(o instanceof Pair)) return false;

    Pair pairo = (Pair) o;

    return this.left.equals(pairo.getLeft()) &&

           this.right.equals(pairo.getRight());

  }

}

And certainly, this subsists in various places on the Net, with fluctuating degrees of completeness and feature. (My sample above is meant to be immutable.)

Related questions

0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4k points)
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...