List strings = Arrays.asList("One", "Two", "Three");
Object stringObject = strings.get(0);
String string = (String) stringObject;
List ints = Arrays.asList(1, 2, 3);
Object intObject = ints.get(0);
int number = (int) intObject;-
Le développeur assume la responsabilité de la compilation
-
Possibilité d’exception à l’exécution
-
-
Comment améliorer la vérification de type à la compilation ?
-
Contrainte de type indiquée entre chevrons
-
Obligatoire pour la déclaration
-
Optionnel pour l’instanciation (Java 7)
-
// Avant Java 7
List<String> strings = new ArrayList<String>();
// Depuis Java 7
List<String> strings = new ArrayList<>();Integer[] integers = { 1, 2, 3, 4 };
Number[] numbers = integers;
numbers[0] = 3.14; // ArrayStoreExceptionList<Integer> integers = Arrays.asList(0, 1, 2, 4);
List<Number> numbers = integers; //compiler errorList<Integer> integers = Arrays.asList(0, 1, 2, 4);
List<? extends Number> numbers = integers;
int zero = integers.get(0);
Number one = numbers.get(1);
integers.add(5);
numbers.add(6); // compiler errorpublic class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
}-
Contrainte sur un type dans la signature d’une méthode
-
Sans que la classe soit générique
-
Via un paramètre supplémentaire dans la signature
public class Foo {
static <T> T id(T t) {
return t;
}
public static void main(String... args) {
Foo foo = new Foo();
String string = Foo.id("Hello");
}
}public class Foo {
static <T extends Number> T max(T a, T b) {
if (a.doubleValue() > b.doubleValue()) {
return a;
}
return b;
}
public static void main(String... args) {
int max1 = Foo.max(1, 2);
double max2 = Foo.max(1.0, 2.0);
Number max = Foo.max(1, 2.0);
}
}