CKTIS / Java
Обобщени типове в Java
Обобщени типове в Java: Generics проверяват типовете при компилация; type erasure премахва повечето типови аргументи и добавя cast или bridge методи, а generic method inference ги извежда от параметрите и целевия тип.
Версия: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Синтаксис
genericsGenerics проверяват типовете при компилация; type erasure премахва повечето типови аргументи и добавя cast или bridge методи, а generic method inference ги извежда от параметрите и целевия тип.
Използвай ? extends T за producer, ? super T за consumer, unbounded wildcard ? за неизвестен тип и intersection bounds като <T extends A & B>, когато са нужни и двата договора.
Generic типовете са инвариантни; raw types премахват проверки, а non-reifiable varargs могат чрез heap pollution да покажат обект под грешен тип.
Capture conversion позволява generic helper безопасно да работи с List.
Изходът показва добавяне чрез ? super, размяна с capture helper, максимум с intersection bound и изведен String тип за first.
Примери
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
static <T> T first(List<? extends T> values) {
return values.get(0);
}
static void addInt(List<? super Integer> values, int value) {
values.add(value);
}
static void swapFirstTwo(List<?> values) {
swapCaptured(values);
}
private static <T> void swapCaptured(List<T> values) {
Collections.swap(values, 0, 1);
}
static <T extends Number & Comparable<T>> T max(T left, T right) {
return left.compareTo(right) >= 0 ? left : right;
}
public static void main(String[] args) {
List<Number> numbers = new ArrayList<>(List.of(1, 2.5));
addInt(numbers, 3);
var words = new ArrayList<>(List.of("a", "b"));
swapFirstTwo(words);
String inferred = first(words);
System.out.println(numbers);
System.out.println(words);
System.out.println(max(4, 7));
System.out.println(inferred);
}
}
Резултат
[1, 2.5, 3] [b, a] 7 b
Изходът показва добавяне чрез ? super, размяна с capture helper, максимум с intersection bound и изведен String тип за first.
Източници
- JLS 4.5: Parameterized Types
- JLS 4.5.1: Type Arguments and Wildcards
- JLS 4.6: Type Erasure
- JLS 4.4: Type Variables and Intersection Bounds
- JLS 5.1.10: Capture Conversion
- JLS 4.8: Raw Types
- JLS 4.12.2: Variables of Reference Type and Heap Pollution
- JLS 18.5.1: Invocation Applicability Inference
- JLS 4.7: Reifiable Types