2

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

}

2 Answers2

1

You are instantiating a raw type:

ArrayDeque a = new ArrayDeque(5);

change it to

ArrayDeque<Integer> a = new ArrayDeque<>(5);

This will remove the need to cast the returned array to Integer[].

P.S., it doesn't make sense for the toArray(E[] a) to define its own generic type parameter E. It should use the parameter defined in the class level.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

You are instantiating a raw type when declaring the ArrayDeque a. You should parameterize it:

ArrayDeque<Integer> a = new ArrayDeque<Integer>(5);
a.addFirst(1);
a.addFirst(2);

Integer [] arr = new Integer[a.size()];
arr=  a.toArray(arr);
rochy_01
  • 161
  • 1
  • 8