简体   繁体   中英

Generic and casting java rules

i have read some generic restrictions

when it comes to casting, it said that we cannot use cast with parameterized types

could anyone explain in what situation we are allowed to cast Object data type to its subclass since generic performs the cast automatically if necessary?

suppose i have the following code:

T[] arrayVar =(T[]) new Object[1] // it causes a compiler warning but still okay

why should i use cast in this situation? doesnt it say that in generic, cast will be done automatically?

Assuming T is not defined as <T extends NotObject> , then

T[] arrayVar =(T[]) new Object[1]// it causes a compiler warning but still okay

post erasure is

Object[] arrayVar = (Object[]) new Object[1];

which has a redundant unchecked cast.

This is not type-safe.

Consider what happens when you do

f(arrayVar)

where

void f(Object[] out) { out[0] = "A string"; }

If that can happen when String is not a subclass of T then you have a type-safety violation.


To solve this problem you can try and create an array of a more specific type. If you can take a parameter of type

Class<T> clazz

then you can create your array thus

T[] varArray = (T[]) Array.newInstance(clazz, 1);

which is more type-safe because trying to do

out[0] = "";

on a Number[] for example will result in an ArrayStoreException at runtime.

It isn't perfectly (dynamically) type-safe, because T might be a type like List<String> and you can still put a List<Number> in a List[] without an ArrayStoreException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM