简体   繁体   中英

How would you create a 2D array of tuples in Java?

I am trying to create a double array of tuples. Would anyone know how this is done?

I basically am looking to have something like the following:

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

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

Each of the indexes of the 2D array would contain a tuple. The tuple would be be the same length as the values array (no matter what it's length was) and would contain various combinations of the values in the values array in order to achieve the desiredGoal value.

You can use java.util.Vector :

so it should be something like:

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);
}

He probably doesn't need the synchronization of Vector , so he should stick to List and ArrayList . Assuming Java 7, try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM