user8913
user8913

Reputation: 53

Java turning two arrays into one two-dimensional array

I have two arrays with the same length in my program, courseGrades and courseCredits, that look something like this:

courseGrades[] = {A, A, B, A, C, A};
courseCredits[] = {1, 2, 1, 3, 2, 1};

I want to combine them into one two-dimensional array that would display like this:

A    A    B    A    C    A
1    2    1    3    2    1

How would I do this in Java? Additionally, how would you refer to each element in this array? Sorry for the very simple question, I'm still a beginner at java.

Upvotes: 1

Views: 4980

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76702

You can create a Pair class, like this:

public class Pair<K, V> {
    public K key;
    public V value;

    public Pair() {}

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }
}

And then you create an array of Pairs. I have not worked in Java for a while, so I might have committed some typos here, but this is the idea:

Pair<char, int> result[] = new Pair<char, int>[keys.length];

for (int i = 0; i < keys.length; i++) {
    result[i] = new Pair<char, int>(keys[i], values[i]);
}

Upvotes: 3

Sweeper
Sweeper

Reputation: 272385

You seem to want to combine an array of strings with an array of ints into a 2D array.

In Java, 2D arrays can only store one kind of thing, so there is no type-safe way to do this. A type-unsafe way to do this would be to store them in an Object[][]:

String[] grades = {"A", "B", "C"};
Integer[] credits = {1, 2, 3};
Object[][] gradesAndCredits = { grades, credits };
for (int i = 0; i < gradesAndCredits.length ; i++) {
    for (int j = 0 ; j < gradesAndCredits[i].length ; j++) {
        System.out.print(gradesAndCredits[i][j] + " ");
    }
    System.out.println();
}

If you want the items in the subarrays as Strings and Integers, you'd need to cast them, which is type-unsafe.

Alternatively, you can store these pairs in a HashMap if it makes sense for one of them to act as the "key" and the other the "value".

String[] grades = {"A", "B", "C"};
Integer[] credits = {1, 2, 3};
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0 ; i < grades.length ; i++) {
    map.put(grades[i], credits[i]);
}

Upvotes: 2

markspace
markspace

Reputation: 11030

Turns out you can assign the references, but only if the array is not an array of primitives, like int or double

String[] letterGrades = { "A", "B", "C" };
int[] numberGrades = { 1, 2, 3 };
Object[][] combined = new Object[2][];
combined[0] = letterGrades;
combined[1] = numberGrades;  // error here

So in this case instead of int[] you'd have to use Integer[] or copy the elements to a new array.

Upvotes: 0

Related Questions