Middle
What is a parameterized type?
sobes.tech AI
Answer from AI
Parameterized types in Java, often called generics, allow defining classes, interfaces, and methods with type parameters. This enhances type safety at compile-time and eliminates the need for type casting.
An example of a parameterized type is List<T>, where T is a type parameter that will be replaced with an actual type when using List.
Advantages of parameterized types:
- Type safety at compile-time: Type mismatch errors are caught during compilation, not at runtime.
- Elimination of type casting: No need for explicit casts when working with collection elements.
- Improved code readability: It is clear what data types the collection or class works with.
Syntax:
Declaring a class with a type parameter:
// T - type parameter
class MyGenericClass<T> {
private T value;
public MyGenericClass(T value) {
this.value = value;
}
public T getValue() {
return this.value;
}
}
Creating an instance of a parameterized type:
// Creating an instance with String type
MyGenericClass<String> stringInstance = new MyGenericClass<>("Hello");
// Creating an instance with Integer type
MyGenericClass<Integer> integerInstance = new MyGenericClass<>(123);
Wildcards:
Used to increase flexibility when working with parameterized types in method signatures.
?(Unbounded Wildcard): Represents any type.? extends UpperBound(Bounded Wildcard - upper bound): Represents any type that is a subtype ofUpperBound.? super LowerBound(Bounded Wildcard - lower bound): Represents any type that is a supertype ofLowerBound.
Example of using bounded wildcards:
import java.util.List;
// Method accepts a list of any types that are subtypes of Number
public void processNumbers(List<? extends Number> numbers) {
for (Number number : numbers) {
System.out.println(number);
}
}
Parameterized types have been a standard part of Java since version 5.