Middle
What are Generics?
sobes.tech AI
Answer from AI
Generics are a mechanism that allows you to write classes, interfaces, and methods that work with data of different types while ensuring type safety during compilation. They enable the creation of reusable components that can work with any data type without losing type information, minimizing runtime type casting errors.
Main advantages:
- Type safety: The compiler checks the correctness of type usage in generic structures.
- Reduced code: A single generic class or method can work with many types.
- Code readability: It is clear which types the component works with.
- Performance improvement (in some cases): The absence of the need for type casting at runtime can slightly improve performance.
Example (Java):
// Example of a generic class
class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
// Using the generic class with different types
Box<Integer> integerBox = new Box<>();
integerBox.setContent(10);
int value = integerBox.getContent(); // Type safety, no need to cast to int
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello");
String text = stringBox.getContent(); // Type safety, no need to cast to String
Example (Python - Type Hinting, approximately similar to Generics):
from typing import TypeVar, Generic
T = TypeVar('T')
class Box(Generic[T]):
def __init__(self) -> None:
self._content: T | None = None
def set_content(self, content: T) -> None:
self._content = content
def get_content(self) -> T | None:
return self._content
# Usage with type hinting
integer_box: Box[int] = Box()
integer_box.set_content(10)
value: int | None = integer_box.get_content() # Helps static analysis tools
string_box: Box[str] = Box()
string_box.set_content("Hello")
text: str | None = string_box.get_content() # Helps static analysis tools