-1

I tested this code :

    Collection l = new ArrayList<Object>();
    l.add(5);
    l.add(2);
    l.add(6);

    Integer[] a=l.toArray(new Integer[0]);//this requires casting to Integer[]

and also look at this code:

   Collection<Object> l = new ArrayList<Object>();
    l.add(5);
    l.add(2);
    l.add(6);

    Integer[] a=l.toArray(new Integer[0]);//this doesn't require casting to Integer[]

first question is

Why first requires casting but second doesn't?

second question is

the size of array doesn't matter any role why we don't pass just class name or by other way?What is the reason for making api like this?

Sarkhan
  • 1,281
  • 1
  • 11
  • 33
  • but question is difference.this is spesific to Collection.because of casting requires at first code but at second doesn't – Sarkhan Mar 21 '16 at 20:07
  • This happens because you are using a raw type. Don't use raw types. Problem solved. – Radiodef Mar 21 '16 at 20:18
  • @Serkhan Thank you for accepting my answer. I've since modified it to explain the cast. Radiodef is right though - you don't really need to worry about this. – Paul Boddington Mar 21 '16 at 20:21

1 Answers1

1

The first question is related to this question. Generic types were not introduced into the language until Java 5, so raw types were allowed for compatibility with earlier code. Raw types work simply by ignoring all generic type information in the method signatures and return types. For this reason, when you use a raw type, the return type of toArray is considered to be Object[] rather than T[]. That is why a cast is required.

The premise of the second question is flawed. The size of the array does matter because if the array is large enough to hold all the elements of the collection, the actual array passed will be filled. Only if the passed array is too small will a new array of the same type be created.

You are correct that it would have been possible for the argument of toArray to have have type Class<T> rather than T[], but the real version has the advantage that it enables arrays to be reused.

Community
  • 1
  • 1
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • I do wish they provided the ` T[] toArray(Class)` overload. And in Java 8 they could have provided the ` T[] toArray(IntFunction)` overload, but they didn't for, well, I have no idea why not. They made other additions to interfaces in Java 8. – Radiodef Mar 21 '16 at 20:22
  • 1
    @Radiodef I agree. `toArray` is a total mess. – Paul Boddington Mar 21 '16 at 20:23