נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
22
חלקPart 4: OOP מתקדםAdvanced OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

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 calling compareTo is allowed.
  • wildcard: ? בטיפוס של פרמטר: List<? extends Number> מקבלת List<Integer> וגם List<Double>.wildcard: ? in a parameter's type: List<? extends Number> accepts a List<Integer> and a List<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> and List<Integer> are the same List. So you can't do new T() or instanceof 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).

Main.java
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;
    }
}
פלטOutput
Dune 1966
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

ויזואלייזר זיכרוןMemory visualizerBox<T>: מחלקה אחת לכל טיפוסBox<T>: one class for every type

מה קורה עכשיו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.

טעות נפוצהCommon mistake

הבדיקה קורית בקומפילציה

The check happens at compile time

Main.java
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);
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
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 error
בעברית פשוטה: In plain words: incompatible 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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.

Main.java
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")));
    }
}
פלטOutput
c 9 pear
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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.

Main.java
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);
    }
}
פלטOutput
6.0 4.0
[1, 2, 0.5]
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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.

טעות נפוצהCommon mistake

צייד באגים: מספר ברשימת מחרוזות

Bug hunter: a number in a list of strings

Main.java
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);
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
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 error
בעברית פשוטה: In plain words: incompatible 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיו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).

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

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.

נבנה על ידיBuilt by Ariel Yohimovich