I have an ArrayList created like this:
public class Main {
public static void main(String[] args) {
// write your code here
ArrayList list1 = new ArrayList();
list1.add(0, 5);
list1.add(1, 3.5);
list1.add(2, 10);
}
}
I am trying to create an array from it, using the toArray method:
public class Main {
public static void main(String[] args) {
// write your code here
ArrayList list1 = new ArrayList();
list1.add(0, 5);
list1.add(1, 3.5);
list1.add(2, 10);
Double[] list2 = list1.toArray(new Double[list1.size()]);
}
}
However, I am getting an error:
(Error:(16, 39) java: incompatible types: java.lang.Object[] ).
So I tried to cast the right side to double:
Double[] list2 = (Double[]) list1.toArray(new Double[list1.size()])
This time i am getting Exception in thread "main". I also tried to declare my ArrayList as double from beginning:
ArrayList<double> list1 = new ArrayList()<double>
With no success. How to do it properly? I know that my problem is probably something very basic.
1 Answer 1
The problem is that you are doing a number of things wrong:
ArrayList list1 = new ArrayList();is incorrect because you are using a raw type. You should have gotten a compiler warning for that.Given the previous
list1.add(0, 5)is incorrect. The5will be boxed as anIntegerbecause that compiler doesn't know that the list is only supposed to containDoublevalues.You were getting this:
(Error:(16, 39) java: incompatible types: java.lang.Object[] ).because you must have done something like this:
Double[] list2 = list1.toArray();You appear to have corrected that in the code that you posted. But the no-args
toArraymethod returns anObject[]containing the list content.ArrayList<double> list1 = new ArrayList()<double>is incorrect because you cannot use a primitive type as a generic type parameter, and because the syntax on the RHS is wrong.The correct version is
ArrayList<Double> list1 = new ArrayList<>();with an empty diamond.
Surprisingly, the best (most efficient) way to code the toArray is:
Double[] list2 = list1.toArray(new Double[0]);
Apparently, the implementation is able to initialize the array faster if it allocates it itself. (Or so I have heard ...)
ArrayList<Double> list = new ArrayList<>();new Double[0]but this should work fine in this case.list1.add(0, 5);tolist1.add(0, 5.0);otherwise to place5to internalObject[]array it would be wrapped inIntgerobject which can't be placed inDouble[]array.