Generic Type Basics
Introduction to Generic Types
Generic types are a powerful feature in Java that enable you to create flexible, reusable code by allowing classes and methods to work with different types while maintaining type safety. They provide a way to write algorithms and data structures that can adapt to various data types without sacrificing compile-time type checking.
Key Concepts
Type Parameters
Generic types use type parameters to define placeholders for specific types. These parameters are enclosed in angle brackets < >
and can represent any class or interface type.
public class GenericBox<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
Type Inference
Java supports type inference, allowing the compiler to automatically determine the type based on context:
GenericBox<String> stringBox = new GenericBox<>(); // Type inferred as String
Generic Type Constraints
Bounded Type Parameters
You can limit the types that can be used with generics by using bounded type parameters:
public class NumberBox<T extends Number> {
private T number;
public double sqrt() {
return Math.sqrt(number.doubleValue());
}
}
Wildcard Types
Wildcards provide additional flexibility in working with generic types:
public void processList(List<? extends Number> numbers) {
// Can work with lists of Number or its subclasses
}
Generic Methods
Generic methods can be defined independently of the class:
public static <E> void printArray(E[] array) {
for (E element : array) {
System.out.print(element + " ");
}
}
Common Use Cases
Comparison of Generic and Non-Generic Approaches
Approach |
Type Safety |
Code Reusability |
Performance |
Non-Generic |
Low |
Limited |
Slightly Better |
Generic |
High |
Excellent |
Minimal Overhead |
Best Practices
- Use generics to create type-safe and reusable code
- Prefer specific type parameters over
Object
- Use bounded type parameters to add constraints
- Avoid excessive type complexity
Practical Example
public class GenericExample {
public static void main(String[] args) {
// Creating generic instances
GenericBox<Integer> intBox = new GenericBox<>();
intBox.set(42);
System.out.println(intBox.get()); // Outputs: 42
GenericBox<String> stringBox = new GenericBox<>();
stringBox.set("LabEx Tutorial");
System.out.println(stringBox.get()); // Outputs: LabEx Tutorial
}
}
Visualization of Generic Type Concept
classDiagram
class GenericBox~T~ {
-T content
+set(T content)
+get() T
}
note "T can be any type"
GenericBox : Type Parameter T
By understanding these fundamental concepts, developers can leverage generic types to write more flexible, type-safe, and maintainable Java code.