我需要将一组n长度的ArrayList转换为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)
任何帮助将不胜感激。此外,如果有一种方法可以将其变成很棒的方法。
答案 0 :(得分:0)
首先,请编程到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]]