将两个单维数组(每个数组由一个arraylist组成)转换为二维数组

时间:2011-12-06 04:03:27

标签: java arrays arraylist

我想知道是否可以使用arraylists将两个单维数组转换为一个二维数组。

这是我的代码:

String[] user = (String[])compList.toArray(new String[usersList.size()]);

String[] computer = (String[])compList.toArray(new String[compList.size()]);

2 个答案:

答案 0 :(得分:1)

我假设

String[] user = (String[])compList.toArray(new String[usersList.size()]);

应该是

String[] user = (String[])usersList.toArray(new String[usersList.size()]);

我不认为这是可能的,假设你想要像

这样的东西
String comuterUser[][]

其中computerUser[0]是用户,computerUser[1]是计算机。您将不得不遍历列表并填充数组。类似的东西(假设两个列表长度相等):

String computerUser[][] = new String[usersList.size()][];
for (int i = 0; i < computerUser.lenth; i++) {
    computerUser[i] = new String[]{ usersList.get(i), compList.get(i) };
}    

最好有两个列表ArrayList用于快速查找。我没有测试过上面的内容,但它应该可以工作。

答案 1 :(得分:0)

您可以使用System.arrayCopy组合数组。

private String[][] wideArray(String[] zero, String[] one) {
    String[][] combined=new String[2][Math.max(zero.length, one.length)];
    System.arraycopy(zero, 0, combined[0], 0, zero.length);
    System.arraycopy(one, 0, combined[1], 0, one.length);
    return combined;
}
相关问题