Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Casting Object to a generic type

In Java when casting from an Object to other types, why does the second line produce a warning related to the cast, but the first one doesn't?

void a(Object o) {
  Integer i = (Integer) o;
  List<Integer> list = (List<Integer>) o;
}

/*Type safety: Unchecked cast from Object to List<Integer>*/
like image 380
Mike Avatar asked Nov 12 '10 22:11

Mike


People also ask

Can you cast to generic in Java?

The Java compiler won't let you cast a generic type across its type parameters because the target type, in general, is neither a subtype nor a supertype.

What is generic type casting in Java?

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java programmer to store a specific type of objects.

Can you type cast an object in Java?

Type Casting in Java – An Introduction Here, the concept of Type casting in Java comes into play. Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting.

How do you pass a generic object in Java?

Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);


2 Answers

It's because the object won't really be checked for being a List<Integer> at execution time due to type erasure. It'll really just be casting it to List. For example:

List<String> strings = new ArrayList<String>();
strings.add("x");
Object o = strings;

// Warning, but will succeeed at execution time
List<Integer> integers = (List<Integer>) o;
Integer i = integers.get(0); // Bang!

See Angelika Langer's Java Generics FAQ for more info, particularly the type erasure section.

like image 161
Jon Skeet Avatar answered Oct 12 '22 22:10

Jon Skeet


Jon's answer is the right one, but occasionally you can't get around that warning (like when you're working with a legacy API). In those cases you can suppress the warning like so:

@SuppressWarnings("unchecked")
List<Integer> list = (List<Integer>) someApiThatReturnsNonGenericList();
like image 33
Brad Cupit Avatar answered Oct 13 '22 00:10

Brad Cupit