0

I need to convert a set of ArrayLists of n length to a JTable.

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

Each of these Arraylists will be the same length.

I'm having some trouble converting them into a multidimensional array where I can eventually use that array in a JTable.

I have tried a number of things.

// 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);

The goal would be to....

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

Any help would be greatly appreciated. Additionally, if there is a way to make this into a method that would be awesome.

Randy G.
  • 111
  • 7

1 Answers1

0

First, please program to the List<Double> interface instead of the ArrayList concrete type. Second, you can use Arrays.asList(double...) to create a List in one line. Finally, you can use List.toArray(T[]) to convert your List<Double> into a Double[]. Like,

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));

Which outputs

[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • I new to java and have a lot to learn. In the case of a List<> vs ArrayList<> what is the difference between ArrayList being concrete and List ? – Randy G. Apr 23 '19 at 03:25
  • [What does it mean to program to a interface?](https://stackoverflow.com/q/1413543/2970947) – Elliott Frisch Apr 23 '19 at 03:36
  • Yeah. From the program side, is there a discernible difference when it comes to handeling a List vs ArrayList – Randy G. Apr 23 '19 at 03:54
  • Every `AbstractList`, `AbstractSequentialList`, `ArrayList`, `AttributeList`, `CopyOnWriteArrayList`, `LinkedList`, `RoleList`, `RoleUnresolvedList`, `Stack` and `Vector` is a `List`. The reverse is not true. So if you program to the `List` interface, you can use any of those (plus any other custom) concrete types. If you program to `ArrayList`, you can only use an `ArrayList`. – Elliott Frisch Apr 23 '19 at 04:06