Java将两个数组变成一个二维数组 [英] Java turning two arrays into one two-dimensional array
问题描述
我的程序中有两个数组,它们的长度相同,分别是courseGrades和courseCredits,它们看起来像这样:
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
我将如何用Java做到这一点?此外,您将如何引用此数组中的每个元素?抱歉,这个非常简单的问题,我还是Java的初学者.
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.
推荐答案
您可以创建一个 Pair
类,如下所示:
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;
}
}
然后创建一个 Pairs
数组.我已经有一段时间没有使用Java了,所以我可能在这里犯了一些错字,但这就是这个想法:
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]);
}
这篇关于Java将两个数组变成一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!