java - 从数组列表创建多维数组
问题描述
我需要将一组长度为 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)
任何帮助将不胜感激。此外,如果有办法把它变成一种很棒的方法。
解决方案
首先,请编程到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]]
推荐阅读
- angular - Angular 8 Fotorama 未在底部显示预览图像
- python - 如何在没有互联网的服务器上安装 wfastcgi?
- php - 找到数字后如何获取字符串的剩余部分
- c# - Unity:场景中的游戏对象增量加载而不是同时加载
- nativescript - 如何在 nativeScript 中捕获滚动偏移 RadListVIew?
- c# - 有没有办法让比较更短
- android - 打开创建新图像资源时出错
- android - Admob Adreward 加载失败,错误代码 0
- java - 你知道 Java 8 格式化程序将链式调用放在单独的行中吗?
- angular - 如何从另一个 [Angular] 调用一个组件的方法