Java turning two arrays into one two-dimensional array

陌路散爱 提交于 2021-02-08 07:05:17

问题


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.


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/51233799/java-turning-two-arrays-into-one-two-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!