Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do generics in Java avoid all ClassCastExceptins?

Since generics are only checked during compile time with Java 5, can they avoid ClassCastExceptions in all situations?

like image 328
Biju CD Avatar asked Aug 14 '09 10:08

Biju CD


People also ask

Do generics prevent type cast errors?

Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.

How do you avoid ClassCastException?

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

Can generics take multiple type parameters?

Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.


1 Answers

The "cast-iron" guarantee that Java 5 generics provides is that you will never see a ClassCastException from the casts inserted by the compiler provided that compilation produced no "unchecked" warnings.

In real life, you often can't avoid unchecked warnings if your code uses legacy (non-generified) libraries. Then the compiler-generated casts can throw ClassCastException, and it's your job to prevent this by ensuring that the values returned by library code are well-typed for your declarations.

Otherwise the situation is unchanged. Outside of generics, if you cast to an incompatible type you'll get a ClassCastException the same way as you always did.

(A good reference for this and other generics questions is Java Generics and Collections.)

like image 62
Maurice Naftalin Avatar answered Sep 19 '22 23:09

Maurice Naftalin