Middle
What are generics in programming?
sobes.tech AI
Answer from AI
Generics are a mechanism in programming languages that allows creating components (classes, interfaces, methods/functions) that work with different data types without losing type safety and without resorting to casting.
Main goals of using Generics:
- Enhanced type safety: The compiler checks types at compile time, detecting errors before program execution.
- Improved code readability: It is clear which data types the component works with.
- Code reuse: You can create one component that works with various types instead of writing multiple versions.
- Reduced casting: It eliminates the need for explicit casting, making the code cleaner and less prone to errors like
ClassCastException(applicable in languages like Java).
Examples of using Generics:
- Collections: Lists (
List), sets (Set), maps (Map) can store elements of a specific type, ensuring that no elements of another type are added. - Methods/functions: A method can work with parameters or return a value of a generic type.
- Classes/interfaces: You can create generic data structures or behavior templates.
Example in Java:
// Generic Pair class
public class Pair<T, U> {
private T first;
private U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
}
public U getSecond() {
return second;
}
}
// Usage
Pair<String, Integer> pair = new Pair<>("Hello", 123);
String str = pair.getFirst(); // No need for casting
int num = pair.getSecond(); // No need for casting
// Pair<String, Integer> wrongPair = new Pair<>(123, "Hello"); // Compilation error: type mismatch
Example in C#:
// Generic Pair class
public class Pair<T, U>
{
public T First { get; set; }
public U Second { get; set; }
public Pair(T first, U second)
{
First = first;
Second = second;
}
}
// Usage
var pair = new Pair<string, int>("Hello", 123);
string str = pair.First; // No need for casting
int num = pair.Second; // No need for casting
// var wrongPair = new Pair<string, int>(123, "Hello"); // Compilation error: type mismatch
Example in TypeScript:
// Generic function to get the first element of an array
function getFirstElement<T>(arr: T[]): T | undefined {
if (arr.length > 0) {
return arr[0];
}
return undefined;
}
// Usage
let numbers: number[] = [1, 2, 3];
let firstNumber = getFirstElement(numbers); // firstNumber is of type number
let words: string[] = ["a", "b", "c"];
let firstWord = getFirstElement(words); // firstWord is of type string
// let mixedArray: (number | string)[] = [1, "a", 2];
// let firstMixed = getFirstElement(mixedArray); // firstMixed is of type number | string
Thus, Generics are a powerful tool for creating flexible, type-safe, and reusable code.