在java中存储数字对

如何在java中存储一组配对数字? 我是使用列表或数组还是其他东西?

例如。 [(1,1),(2,1),(3,5)]

有几个选择:

编写自定义IntPair类

 class IntPair { // Ideally, name the class after whatever you're actually using // the int pairs *for.* final int x; final int y; IntPair(int x, int y) {this.x=x;this.y=y;} // depending on your use case, equals? hashCode? More methods? } 

然后创建一个IntPair[]List

或者,创建一个二维数组new int[n][2] ,并将这些行视为成对。

由于某些原因,Java没有内置的Pair类,但最引人注目的是编写一个具有相同function的类很容易,但是对于类,它的字段,它有更多启发性,有用的名称,及其方法。

如果我们更多地了解您实际使用它的内容,我们可能会提供更详细的建议 – 就我们所知,我们可以在这里找到适合的Map

 class Pair { T p1, p2; Pair(T p1, T p2) { this.p1 = p1; this.p2 = p2; } Pair pair = new Pair(1,2); int i1 = pair.p1; int i2 = pair.p2; 

你也可以输入getter,setter,equals,hashcode等。

如果您可以使用低级结构并且迫切需要紧凑forms的“文字”forms的“一对” – 这在unit testing中发生,当我需要一组灯具时 – 您可以简单地使用一个数组数组:

 int[][] squares = { { 1, 1 }, { 2, 4 }, { 3, 9 } }; 

但请记住,这样的类型没有语义 – 这一切都取决于正确使用,如果你在你真正想要squares[1][0] squares[0][1]时键入squares[0][1] ,编译器就不会给你一个警告squares[1][0]

如果你需要避免重复,那么HashSet将是一个不错的选择,但它不会是一个ArrayList可以工作。

 Class IntPair(){ int i; int j; } HashSet set = new HashSet(); 

要么

 ArrayList list = new ArrayList();