价值对的Java集合? (元组?) [英] A Java collection of value pairs? (tuples?)

查看:111
本文介绍了价值对的Java集合? (元组?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢Java有一个Map,你可以在其中定义地图中每个条目的类型,例如< String,Integer>

I like how Java has a Map where you can define the types of each entry in the map, for example <String, Integer>.

我正在寻找的是一种集合,其中集合中的每个元素都是一对值。对中的每个值都可以有自己的类型(如上面的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).

基本上我希望能够定义类型< String,Integer> 或任何其他2的ARRAY类型。

Essentially I want to be able to define an ARRAY of type <String,Integer> or any other 2 types.

我意识到我可以创建一个只有2个变量的类,但这看起来过于冗长。

I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.

我也意识到我可以使用2D数组,但由于我需要使用不同类型,我必须使它们成为OBJECT数组,然后我必须一直投。

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!

推荐答案

Pair类是其中一个gimme泛型示例,它们很容易自行编写。例如,在我的头顶:

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.)

这篇关于价值对的Java集合? (元组?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆