Java Generics
Generics Nədir?
Java Generics (Java 5) tip təhlükəsizliyi təmin edir, compile zamanı tip yoxlaması aparır və ClassCastException xətalarının qarşısını alır.
Üstünlükləri
- Tip təhlükəsizliyi - Compile zamanı yoxlama
- Casting-in aradan qaldırılması - Avtomatik tip çevirmələri
- Kod təkrarının azaldılması - Eyni kod müxtəlif tiplər üçün
Generic Class
public class Box<T> {
private T value;
public Box(T value) { this.value = value; }
public T getValue() { return value; }
}
// İstifadə
Box<String> stringBox = new Box<>("Salam");
Box<Integer> intBox = new Box<>(123);
Generic Metodlar
public class Util {
public static <T> T getFirst(T... elements) {
return elements[0];
}
}
// İstifadə
String str = Util.getFirst("A", "B", "C");
Integer num = Util.getFirst(1, 2, 3);
Bounded Type Parameters
public class NumberBox<T extends Number> {
private T value;
public NumberBox(T value) { this.value = value; }
public double getDouble() {
return value.doubleValue();
}
}
Wildcards
Unbounded Wildcards (?)
public void printList(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
}
Upper Bounded (? extends)
public double sum(List<? extends Number> list) {
double total = 0;
for (Number num : list) {
total += num.doubleValue();
}
return total;
}
Lower Bounded (? super)
public void addIntegers(List<? super Integer> list) {
list.add(1);
list.add(2);
}
Type Erasure
Generics məlumatı compile zamanından sonra silinir (type erasure). Runtime-da bütün generic tiplər raw type olur.
List<String> strings = new ArrayList<>();
List<Integer> integers = new ArrayList<>();
// Runtime-da hər ikisi ArrayList tipindədir
Best Practices
-
Diamond operator istifadə edin:
List<String> list = new ArrayList<>(); -
Raw types istifadə etməyin:
List list = new ArrayList(); // ❌ Pis
List<String> list = new ArrayList<>(); // ✅ Yaxşı -
PECS qaydasını yadda saxlayın:
- Producer Extends
- Consumer Super