Middle
What are Generics and what are they used for?
sobes.tech AI
Answer from AI
Generics in Java allow creating classes, interfaces, and methods that work with parameterized types.
Main purposes of Generics:
- Enhanced type safety: The compiler checks types at compile time, preventing
ClassCastExceptionat runtime. - Elimination of type casting: No need to manually cast types when retrieving elements from collections.
- Creating more flexible and reusable code: You can write generic algorithms and data structures applicable to various data types.
Example without Generics:
// Before Java 5
import java.util.ArrayList;
import java.util.List;
public class OldStyleList {
public static void main(String[] args) {
List list = new ArrayList(); // no typing
list.add("hello");
list.add(123); // can add any object
String s = (String) list.get(0); // requires casting
Integer i = (Integer) list.get(1); // requires casting
// Possible cast error
// String error = (String) list.get(1); // ClassCastException
System.out.println(s);
System.out.println(i);
}
}
Example with Generics:
// Using Generics
import java.util.ArrayList;
import java.util.List;
public class GenericList {
public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list of strings
list.add("hello");
// list.add(123); // compile-time error - cannot add Integer
String s = list.get(0); // no need for casting
// Cannot add other types, prevents errors
// List<Integer> intList = new ArrayList<>();
// intList.add("world"); // compile-time error
System.out.println(s);
}
}
Generics are also used in:
- Classes:
ArrayList<E>,HashMap<K, V> - Interfaces:
List<E>,Map<K, V> - Methods:
<T> void printArray(T[] array) - Type bounds:
<T extends Comparable<T>>(constraint on types implementingComparable)
Java's implementation of Generics is based on "type erasure" at compile time. This means that information about generic types is removed, and at runtime, the JVM operates on raw types. This ensures backward compatibility with older Java versions but has some limitations.