您将如何在Java中创建元组的二维数组?

时间:2013-04-02 03:43:37

标签: java tuples multidimensional-array

我正在尝试创建一个双元组元组。有谁知道这是怎么做的?

我基本上希望得到以下内容:

int[] values = {5, 1, 7}; // This array length can vary with different values
int desiredGoal = 77;

int data[][] = new int[values.length][desiredGoal + 1];

2D数组的每个索引都包含一个元组。元组的长度与值数组的长度相同(无论它的长度是多少),并且将包含values数组中值的各种组合,以便获得所需的Goal值。

2 个答案:

答案 0 :(得分:0)

您可以使用java.util.Vector

所以它应该是这样的:

Vector<Integer> values = new Vector<Integer>(Arrays.asList([5,1,7]));
Vector<Vector<Integer>> data = new Vector<Vector<Integer>>(values.size()) 
//you'll also need to actually create the inner vector objects:
for (int i = 0; i<values.size(); i++){
   data.set(i,new Vector<Integer>(desiredGoal + 1);
}

答案 1 :(得分:0)

他可能不需要Vector的同步,所以他应该坚持ListArrayList。假设Java 7,试试这个:

List<Integer> values = new ArrayList<>();
Collections.addAll(values, 5, 1, 7);
int desiredGoal = 77;
List<List<Integer>> data = new List<>(); 
// Create the inner lists:
for (final int ignored: values) {
    data.add(new ArrayList<>(desiredGoal + 1));
    // List<Integer> is wanted, so use type inference.
}
相关问题