2

I was reading Effective Java by Josh Bloch and I came across an Item 24: Eliminate unchecked warnings.

In that they give an example of toArray() method of the class which generates unchecked warning.

    ArrayList.java:305: warning: [unchecked] unchecked cast
    found : Object[], required: T[]
    return (T[]) Arrays.copyOf(elements, size, a.getClass());

I am not bale to understand how the compiler is diagnosing that it would return Object[]?

May be I am not able to understand the type erasure phenomena behind it.

Can somebody explain me how Object[] would be returned?

Thanks in advance.

Sam
  • 2,352
  • 4
  • 32
  • 45

1 Answers1

0

checking its API docs it clearly says that

public static <T,U> T[] copyOf(U[] original,
                           int newLength,
                           Class<? extends T[]> newType)

3rd argument specifies the newType - the class of the copy to be returned and its return statement states
:

Returns:
     a copy of the original array, truncated or padded with nulls to obtain the 
     specified length

check this as well for Object[] return and
What is more efficient: System.arraycopy vs Arrays.copyOf?

Edit: check for type erasure in oracle docs tutorial http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

it says:

Replace all type parameters (like T K V) in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.

Community
  • 1
  • 1
exexzian
  • 7,782
  • 6
  • 41
  • 52
  • Still bit confused. But I am not able to get how Object[] is created ? Can you please explain me that. – Sam Feb 24 '13 at 07:24
  • I got it the copyOf method returns Object[] and not anything of type T[] and so is the warning. – Sam Feb 24 '13 at 07:29
  • 1
    @Sam was about to comment same thing check this for more info http://docs.oracle.com/javase/tutorial/java/generics/erasure.html – exexzian Feb 24 '13 at 07:30