Java Interview Questions - Generics

Here are the most popular Java interview questions about generics.

See all questions

What are Generics in Java?


Generics are a feature that allow a class to be parameterized into sub-types. Generics provide compile-time safety and prevent runtime typecasting errors resulting in ClassCastException. Without generics, a user is forced to use the lowest common base-class and then typecast the object, which is highly error-prone and has no type-safety.

Why won't the following code sample compile and how would you fix it?


This will raise a compilation error. It is incorrect to pass a List<String> to a method accepting List<Object>. A List<Object> can accept Strings, but t1 can only accept List<Object>.

Either ls should be changed to List<Object>, or lo should be made Generic: List<? extends Object> lo

What is type erasure?


The Type information used for Generic objects is only available at compile time. The compiler removes all the type information when converting to byte-code. This makes the type information unavailable at Runtime and the Generic type is converted to Raw type. The compiler provides checks at compile time to prevent runtime errors for incorrect type i

...

Is the following code compile-time and run-time safe?


Yes, this code is compile-time and run-time safe.

I and K are Generic type parameters used to ensure type safety.

The extends keyword in the first line defines the scope of the I parameter. The I parameter can only be a sub-type of List of type K. K by default extends Object.

The second extends keyword is used for inheriting c

...

Looking for developers?