GenericsGenerics
מחלקות ומתודות גנריות, bounded types, wildcards ו-PECS, ו-type erasure.
Generic classes and methods, bounded types, wildcards and PECS, and type erasure.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- מחלקה גנרית: מחלקה עם פרמטר טיפוס:
class Box<T>. כל שימוש קובע מה זה T:Box<String>,Box<Integer>.generic class: A class with a type parameter:class Box<T>. Each use decides what T is:Box<String>,Box<Integer>. - פרמטר טיפוס: השם בסוגריים המשולשים (
T,A,B,K,V). בתוך המחלקה הוא מתנהג כמו טיפוס רגיל.type parameter: The name in angle brackets (T,A,B,K,V). Inside the class it acts like a normal type. - מתודה גנרית: מתודה עם פרמטר טיפוס משלה, לפני טיפוס ההחזרה:
static <T> T last(List<T> list). javac מסיק את T מהארגומנטים.generic method: A method with its own type parameter, before the return type:static <T> T last(List<T> list). javac infers T from the arguments. - טיפוס מוגבל:
<T extends Comparable<T>>: T יכול להיות רק טיפוס שיודע להשוות את עצמו, ולכן מותר לקרוא ל-compareTo.bounded type:<T extends Comparable<T>>: T can only be a type that can compare itself, so callingcompareTois allowed. - wildcard:
?בטיפוס של פרמטר:List<? extends Number>מקבלתList<Integer>וגםList<Double>.wildcard:?in a parameter's type:List<? extends Number>accepts aList<Integer>and aList<Double>. - PECS: Producer Extends, Consumer Super: רשימה שרק קוראים ממנה היא
? extends T, ורשימה שרק כותבים אליה היא? super T.PECS: Producer Extends, Consumer Super: a list you only read from is? extends T, and a list you only write to is? super T. - מחיקת טיפוסים: אחרי הקומפילציה
List<String>ו-List<Integer>הם אותוList. לכן אי אפשרnew T()אוinstanceof List<String>: בזמן ריצה המידע כבר לא קיים.type erasure: After compiling,List<String>andList<Integer>are the sameList. So you can't donew T()orinstanceof List<String>: at run time the information is gone.
02Box<T>: מחלקה אחת לכל טיפוסBox<T>: one class for every type
T הוא פרמטר טיפוס. Box<String> מחזירה String בלי המרה, ו-Box<Integer> מחזירה Integer (וה-autoboxing הופך אותו ל-int).
T is a type parameter. Box<String> returns a String with no cast, and Box<Integer> returns an Integer (autoboxing turns it into an int).
public class Main {
public static void main(String[] args) {
Box<String> name = new Box<>("Dune");
Box<Integer> year = new Box<>(1965);
String n = name.get();
int y = year.get();
System.out.println(n + " " + (y + 1));
}
}
class Box<T> {
private final T value;
Box(T value) {
this.value = value;
}
T get() {
return value;
}
}Dune 1966
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
פלטOutput
Stack: משתנים בכל מתודהStack: each method's variables
Heap: העצמיםHeap: the objects
03הבדיקה קורית בקומפילציהThe check happens at compile time
בלי generics, מספר היה נכנס לרשימת מחרוזות ומפיל את התוכנית מאוחר יותר. עם List<String>, javac עוצר מיד, בשורה שבה הטעות.
Without generics, a number would get into a list of strings and crash the program later. With List<String>, javac stops right away, on the line with the mistake.
הבדיקה קורית בקומפילציה
The check happens at compile time
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> titles = new ArrayList<>();
titles.add("Dune");
titles.add(1965);
}
}Main.java:8: error: incompatible types: int cannot be converted to String
titles.add(1965);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorincompatible types: int cannot be converted to String: לרשימה של String נכנסות רק מחרוזות.incompatible types: int cannot be converted to String: only strings go into a list of String.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04מתודות גנריות וגבולותGeneric methods and bounds
last עובדת לכל רשימה. ב-max, הגבול T extends Comparable<T> מבטיח שיש compareTo, ולכן אותה מתודה עובדת גם למספרים וגם למחרוזות.
last works for any list. In max, the bound T extends Comparable<T> guarantees there's a compareTo, so the same method works for numbers and strings alike.
import java.util.List;
public class Main {
static <T> T last(List<T> list) {
return list.get(list.size() - 1);
}
static <T extends Comparable<T>> T max(List<T> list) {
T best = list.get(0);
for (T x : list) {
if (x.compareTo(best) > 0) {
best = x;
}
}
return best;
}
public static void main(String[] args) {
System.out.println(last(List.of("a", "b", "c")) + " " + max(List.of(3, 9, 4)) + " " + max(List.of("pear", "apple")));
}
}c 9 pear
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05wildcards ו-PECSWildcards and PECS
sum רק קוראת מספרים, ולכן ? extends Number (מקבלת List<Integer> ו-List<Double>). addNumbers רק כותבת Integer, ולכן ? super Integer (מקבלת List<Number>). זה PECS.
sum only reads numbers, so ? extends Number (it accepts List<Integer> and List<Double>). addNumbers only writes Integers, so ? super Integer (it accepts a List<Number>). That's PECS.
import java.util.ArrayList;
import java.util.List;
public class Main {
static double sum(List<? extends Number> nums) {
double s = 0;
for (Number n : nums) {
s += n.doubleValue();
}
return s;
}
static void addNumbers(List<? super Integer> out) {
out.add(1);
out.add(2);
}
public static void main(String[] args) {
System.out.println(sum(List.of(1, 2, 3)) + " " + sum(List.of(1.5, 2.5)));
List<Number> mixed = new ArrayList<>();
addNumbers(mixed);
mixed.add(0.5);
System.out.println(mixed);
}
}6.0 4.0 [1, 2, 0.5]
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.
These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.
צייד באגים: מספר ברשימת מחרוזות
Bug hunter: a number in a list of strings
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> labels = new ArrayList<>();
labels.add("Dune");
labels.add(1965);
System.out.println(labels);
}
}Main.java:8: error: incompatible types: int cannot be converted to String
labels.add(1965);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorincompatible types: int cannot be converted to String: javac שומר שלרשימה ייכנסו רק מחרוזות.incompatible types: int cannot be converted to String: javac makes sure only strings go into the list.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
07הצעד של היום בפרויקט מדףToday's step in the Shelf project
class Shelf<T> עם שם ו-List<T> פרטית: add, get, size, ו-toString titles[Dune, Emma]. צרו Shelf<String> ו-Shelf<Integer>, הדפיסו את שניהם, ואז Dune 3780 (get מחזיר את הטיפוס הנכון בלי המרה).
class Shelf<T> with a name and a private List<T>: add, get, size, and a toString titles[Dune, Emma]. Create a Shelf<String> and a Shelf<Integer>, print both, then Dune 3780 (get returns the right type with no cast).
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.