I have problem with the toArray method. In this example i am using Integer and solved it by casting Integer, but the method should work for all types, without casting in main.
why cant i use one of these two in my main method?
arr = (T[]) a.toArray(arr) ;
or even
arr = a.toArray(arr)
I get a type mismatch: cannot convert from object[] to Integer[]
both size() and addFirst() works.
public static void main(String[] args) {
ArrayDeque a = new ArrayDeque(5);
a.addFirst(1);
a.addFirst(2);
Integer [] arr = new Integer[a.size()];
arr= (Integer[]) a.toArray(arr);
System.out.println(Arrays.toString(arr));
}
public class ArrayDeque<E> implements IDeque<E> {
private int counter= 0;
private E[] deque;
@SuppressWarnings("unchecked")
public ArrayDeque(int size) {
deque = (E[]) new Object[size];
}
public <E> E[] toArray(E[] a) {
return (E[]) Arrays.copyOf(deque, counter, a.getClass());
}
}