[英]How would you create a 2D array of tuples in Java?
我正在尝试创建一个双元组数组。 有人知道这是怎么做的吗?
我基本上希望拥有类似以下内容的东西:
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数组的长度相同(无论它的长度是多少),并且将在values数组中包含值的各种组合以实现期望的Goal值。
您可以使用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);
}
他可能不需要Vector
的同步,因此他应该坚持使用List
和ArrayList
。 假设使用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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.