首页 > 解决方案 > 从数组列表创建多维数组

问题描述

我需要将一组长度为 n 的 ArrayLists 转换为 JTable。

ArrayList<Double> operand1 = new ArrayList<>();
ArrayList<Double> operand2 = new ArrayList<>();
ArrayList<Double> userAnswer = new ArrayList<>();
ArrayList<Double> correctAnswer = new ArrayList<>();

这些 Arraylist 中的每一个都将具有相同的长度。

我在将它们转换为多维数组时遇到了一些麻烦,我最终可以在 JTable 中使用该数组。

我已经尝试了很多东西。

// converting the single list to an array: error obj to double
Double [] arr = new Double[operand1.size()];
arr = operand.toArray();

// Shot in the dark
arr = Arrays.copyOf(operand1.toString(), operand1.size(), Double.class);

目标是......

// Needs a name for each column
Double [][] data = {operand1, operand2, userAnswer, correctAnswer}
//or individually add them via
JTable table = new Table();
table.add(operand)

任何帮助将不胜感激。此外,如果有办法把它变成一种很棒的方法。

标签: java

解决方案


首先,请编程到List<Double>接口而不是ArrayList具体类型。其次,您可以使用在一条线上Arrays.asList(double...)创建一个List。最后,您可以使用List.toArray(T[])将您的List<Double>转换为Double[]. 喜欢,

List<Double> operand1 = Arrays.asList(1.0, 2.0);
List<Double> operand2 = Arrays.asList(3.0, 4.0);
List<Double> userAnswer = Arrays.asList(5.0, 6.0);
List<Double> correctAnswer = Arrays.asList(7.0, 8.0);
Double[][] data = { operand1.toArray(new Double[0]), operand2.toArray(new Double[0]),
        userAnswer.toArray(new Double[0]), correctAnswer.toArray(new Double[0]) };
System.out.println(Arrays.deepToString(data));

哪个输出

[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]

推荐阅读