0

When I write generic class in Java, I use below code

public ResizableArray() {
    this.count=0;
    this.elements = (T[]) new Object[0];
}

However I get a warning:

Type Safety: Unchecked Cast from Object[] to T[]

Why do I get this warning?

lkamal
  • 3,788
  • 1
  • 20
  • 34
vavio
  • 17
  • 2
  • 3
  • 1
    It will be more informative if you could add more code into this question to show where is visible. – lkamal Nov 03 '13 at 19:42

2 Answers2

2

You're creating an Object[] (that is, an array of instances of class "Object", so basically an array of anything). You're casting it into an T[] (that is an array that can ONLY contain instances of class T). You don't test if the objects in the array (I know there are none, but the compiler doesn't) actually IS a T - if it isn't, the cast will throw an ClassCastException at runtime. That's why you get the warning.

Johannes H.
  • 5,875
  • 1
  • 20
  • 40
  • how can i avoid this ? – vavio Nov 03 '13 at 19:59
  • You cannot - at least not without changing a little more. Arrays simple are never generic, so you cannot create arrays from generic types. For any more suggestions you need to show us some more code so we can take a look at the bigger picture to see if, where and what could be changed. – Johannes H. Nov 03 '13 at 20:06
  • "if it isn't, the cast will throw an ClassCastException at runtime" Nope. – newacct Nov 04 '13 at 02:37
  • @newacct: Nope? Well, yes! That exception is not thrown when the casting is done, but it is when you actually read the objects in that array. – Johannes H. Nov 04 '13 at 02:38
  • @JohannesH.: No. You can read the objects in the array fine. A problem will only occur if you expose the type of the array variable to the outside. – newacct Nov 04 '13 at 05:36
  • @newacct: If I'd do `T myWhatever=((T[]) new Object[] {new Integer()})[0];`, that would not give my an exception if T is not Integer? I doubt that (but I cannot try right now) – Johannes H. Nov 04 '13 at 08:06
  • @JohannesH.: Nope, it will not. Think about it after type erasure. – newacct Nov 04 '13 at 10:11
1

If T is anything else but Object, you are basically lying with that downcast. This is because the type of Java arrays, unlike generic types, is reified. In other words,

boolean isStringArray(Object[] os) { return os instanceof String[]; }

called with

System.out.println(isStringArray(new Object[]));

actually prints false: the runtime knows the component type of the array.

What you would really like to do there is return new T[], but you have probably found out this isn't allowed, and it isn't allowed due to exactly the mismatch between generics and array types described above.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436