Перейти к содержимому

Java Arrays vs Generics: Covariance, Erasure and Why new T[] Won't Compile | Effective Java L28

The Modern SDE

0:00 / 0:00

Java Arrays vs Generics: Covariance, Erasure and Why new T[] Won't Compile | Effective Java L28

4 просмотра · 12 часов назад
The Modern SDE
1,25 тыс. подписчиков
4 просмотра · 12 часов назад
Lecture 28 of the Effective Java Masterclass by Engineer X · Part 4: Generics. In this lecture • Arrays are covariant: a String stored into an Integer[] through an Object[] compiles and throws ArrayStoreException • Generics are invariant: the same mistake with a List is a compile error • Arrays are reified, generics are erased: an Integer[] knows its element type, every ArrayList has the same class • Why generic array creation is illegal: an aliased generic array could hold the wrong list and a hidden cast fails later (shown with a faked array) • Non-reifiable types (E, List‹E›, List‹String›) and the one exception, List‹?›[] • A round-robin dispatcher: an unchecked cast to T[] vs a warning-free List‹T›, and the small price of a List • Modern Java: List.of (9), List.copyOf (10), toArray(String[]::new) (11), Stream.toList (16), getFirst/getLast (21), still no primitive generics • Interview: why you can't write new T[10], how ArrayList copes, and the workarounds Chapters 0:00 A String in an Integer array 0:44 Covariant vs invariant 1:27 Reified vs erased 2:22 Why new T[] won't compile 3:36 What can't go in an array 4:23 When in doubt, use a List 5:36 Modern Java: copies and toArray 6:37 Interview: why no new T[10]? 7:19 Recap and quiz Follows the topics of Effective Java, 3rd edition, by Joshua Bloch (Item 28: Prefer lists to arrays). Every explanation, example and line of code in this lecture is original. Previous lecture: L027 Java Unchecked Warnings: When @SuppressWarnings Is Safe (and When It Lies) Next lecture: L029 Java Generic Classes: Build an Array-Backed Generic Type the Safe Way #Java #EffectiveJava #JavaInterview #SeniorJavaDeveloper #JavaBestPractices #EngineerX #JavaGenerics #JavaArrays #TypeErasure #EffectiveJava #JavaInterview