DEV Community

Tapas Pal
Tapas Pal

Posted on

Generics in Java Interview Q&A

Java Generics is one of the MOST important Java concepts.
If you understand Generics properly:
collections become safer
code becomes reusable
compile-time bugs reduce dramatically

A generic type is a generic class or interface that is parameterized over types.

What Are Generics?
Generics allow classes, interfaces, and methods to work with:
different data types safely
without rewriting code.
The Diamond
In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond. For example, you can create an instance of Box with the following
statement:

Box<Integer> integerBox = new Box<>();
Enter fullscreen mode Exit fullscreen mode

Generic Class

class Box<T> {
    T value;
    void set(T value) {
        this.value = value;
    }
    T get() {
        return value;
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage

Box<String> box =
        new Box<>();
box.set("Hello");
String s = box.get();
Enter fullscreen mode Exit fullscreen mode

What Does Mean?
T means:Type parameter
Placeholder for actual type.
Common Generic Type Names
Symbol - Meaning
T - Type
E - Element
K - Key
V - Value
N - Number

Same class reused.

Box<Integer> intBox = new Box<>();
Box<String> strBox = new Box<>();
Enter fullscreen mode Exit fullscreen mode

DISADVANTAGES OF GENERICS
Now let us discuss the IMPORTANT limitations.

1. Type Erasure
MOST IMPORTANT limitation.
Java removes generic type information at runtime.
Example

List<String> list = new ArrayList<>();
Enter fullscreen mode Exit fullscreen mode

At runtime becomes: List
Generic type removed. Why?
Backward compatibility with old Java.
Consequences of Type Erasure
Cannot Do This

if(obj instanceof List<String>)
Enter fullscreen mode Exit fullscreen mode

Compile-time error.

Cannot Create Generic Array

T[] arr = new T[10];
Enter fullscreen mode Exit fullscreen mode

Not allowed. Why?
Because runtime type unknown.

2. Primitive Types Not Allowed
Cannot use: List<int>
Only objects allowed.
Correct List<Integer>
Uses wrapper classes.
Problem
Wrapper classes add:
memory overhead
boxing/unboxing cost
Example

List<Integer> list = new ArrayList<>();
list.add(10);
Enter fullscreen mode Exit fullscreen mode

Actually becomes:
Integer.valueOf(10)
Auto-boxing.

3. Cannot Create Static Generic Fields
Invalid

class Test<T> {
    static T value;
}
Enter fullscreen mode Exit fullscreen mode

Why?
A static field belongs to the class,
but a generic type belongs to the object instance/type parameter.

These two concepts conflict.
First Understand Static Variables
Static variables are:shared across ALL objects
Only ONE copy exists.

Top comments (0)