A Java collection of value pairs? (tuples?)

2018-12-31 08:39发布

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!

标签: java
17条回答
孤独寂梦人
2楼-- · 2018-12-31 09:10
琉璃瓶的回忆
3楼-- · 2018-12-31 09:12

The Pair class is one of those "gimme" generics examples that is easy enough to write on your own. For example, 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 yes, this exists in multiple places on the Net, with varying degrees of completeness and feature. (My example above is intended to be immutable.)

查看更多
千与千寻千般痛.
4楼-- · 2018-12-31 09:12

You could write a generic Pair<A, B> class and use this in an array or list. Yes, you have to write a class, but you can reuse the same class for all types, so you only have to do it once.

查看更多
姐姐魅力值爆表
5楼-- · 2018-12-31 09:13

I was going to ask if you would not want to just use a List<Pair<T, U>>? but then, of course, the JDK doesn't have a Pair<> class. But a quick Google found one on both Wikipedia, and forums.sun.com. Cheers

查看更多
临风纵饮
6楼-- · 2018-12-31 09:13

just create a class like

class tuples 
{ 
int x;
int y;
} 

then create List of this objects of tuples

List<tuples> list = new ArrayList<tuples>();

so you can also implement other new data structures in the same way.

查看更多
长期被迫恋爱
7楼-- · 2018-12-31 09:14

Map.Entry

These built-in classes are an option, too. Both implement the Map.Entry interface.

UML diagram of Map.Entry interface with pair of implementing classes

查看更多
登录 后发表回答