נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
GenericsGenerics
מפגש 22: מחלקות ומתודות גנריות, bounded types, wildcards ו-PECS, ו-type erasure.Session 22: Generic classes and methods, bounded types, wildcards and PECS, and type erasure.
מחלקות ומתודות גנריות, bounded types, wildcards ו-PECS, ו-type erasure. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Generic classes and methods, bounded types, wildcards and PECS, and type erasure. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- Box<T>: מחלקה אחת לכל טיפוסBox<T>: one class for every type
- הבדיקה קורית בקומפילציהThe check happens at compile time
- מתודות גנריות וגבולותGeneric methods and bounds
- wildcards ו-PECSWildcards and PECS
- טעויות נפוצותCommon mistakes
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- מחלקה גנרית: מחלקה עם פרמטר טיפוס:generic class: A class with a type parameter:
- פרמטר טיפוס: השם בסוגריים המשולשים (
T, A, B, K, V).type parameter: The name in angle brackets (T, A, B, K, V). - מתודה גנרית: מתודה עם פרמטר טיפוס משלה, לפני טיפוס ההחזרה:generic method: A method with its own type parameter, before the return type:
- טיפוס מוגבל:
<T extends Comparable<T>>:bounded type: <T extends Comparable<T>>: - wildcard:
? בטיפוס של פרמטר:wildcard: ? in a parameter's type: - PECS: Producer Extends, Consumer Super:PECS: Producer Extends, Consumer Super:
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
Box<T>: מחלקה אחת לכל טיפוסBox<T>: one class for every type
Box<T>: מחלקה אחת לכל טיפוסBox<T>: one class for every type
T הוא פרמטר טיפוס.T is a type parameter.Box<String> מחזירה String בלי המרה, ו-Box<Integer> מחזירה Integer (וה-autoboxing הופך אותו ל-int).Box<String> returns a String with no cast, and Box<Integer> returns an Integer (autoboxing turns it into an int).
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).נושאTopic 3
הבדיקה קורית בקומפילציהThe check happens at compile time
הבדיקה קורית בקומפילציהThe check happens at compile time
- בלי generics, מספר היה נכנס לרשימת מחרוזות ומפיל את התוכנית מאוחר יותר.Without generics, a number would get into a list of strings and crash the program later.
- עם
List<String>, javac עוצר מיד, בשורה שבה הטעות.With List<String>, javac stops right away, on the line with the mistake.
בלי 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.נושאTopic 4
מתודות גנריות וגבולותGeneric methods and bounds
מתודות גנריות וגבולותGeneric methods and bounds
last עובדת לכל רשימה.last works for any list.- ב-
max, הגבול T extends Comparable<T> מבטיח שיש compareTo, ולכן אותה מתודה עובדת גם למספרים וגם למחרוזות.In max, the bound T extends Comparable<T> guarantees there's a compareTo, so the same method works for numbers and strings alike.
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.נושאTopic 5
wildcards ו-PECSWildcards and PECS
wildcards ו-PECSWildcards and PECS
sum רק קוראת מספרים, ולכן `?sum only reads numbers, so `?- extends Number
(מקבלת List<Integer> ו-List<Double>`).extends Number (it accepts List<Integer> and List<Double>`). addNumbers רק כותבת Integer, ולכן `?addNumbers only writes Integers, so `?
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.נושאTopic 6
טעויות נפוצותCommon mistakes
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
- `incompatible types:`incompatible types:
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.נושאTopic 7
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 22: Shelf<T> גנריShelf, step 22: a generic Shelf<T>
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).מחלקה גנרית: מחלקה עם פרמטר טיפוס:generic class: A class with a type parameter:
המונחים של המפגשThis session's termsפרמטר טיפוס: השם בסוגריים המשולשים (T, A, B, K, V).type parameter: The name in angle brackets (T, A, B, K, V).
המונחים של המפגשThis session's termsמתודה גנרית: מתודה עם פרמטר טיפוס משלה, לפני טיפוס ההחזרה:generic method: A method with its own type parameter, before the return type:
המונחים של המפגשThis session's termsטיפוס מוגבל: <T extends Comparable<T>>:bounded type: <T extends Comparable<T>>:
המונחים של המפגשThis session's termswildcard: ? בטיפוס של פרמטר:wildcard: ? in a parameter's type:
המונחים של המפגשThis session's termsPECS: Producer Extends, Consumer Super:PECS: Producer Extends, Consumer Super:
המונחים של המפגשThis session's termsBox<T>: מחלקה אחת לכל טיפוסBox<T>: one class for every typeBox<String> מחזירה String בלי המרה, ו-Box<Integer> מחזירה Integer (וה-autoboxing הופך אותו ל-int).Box<String> returns a String with no cast, and Box<Integer> returns an Integer (autoboxing turns it into an int).
Box<T>: מחלקה אחת לכל טיפוסBox<T>: one class for every typeבלי generics, מספר היה נכנס לרשימת מחרוזות ומפיל את התוכנית מאוחר יותר.Without generics, a number would get into a list of strings and crash the program later.
הבדיקה קורית בקומפילציהThe check happens at compile timeעם List<String>, javac עוצר מיד, בשורה שבה הטעות.With List<String>, javac stops right away, on the line with the mistake.
הבדיקה קורית בקומפילציהThe check happens at compile timelast עובדת לכל רשימה.last works for any list.
מתודות גנריות וגבולותGeneric methods and boundsב-max, הגבול T extends Comparable<T> מבטיח שיש compareTo, ולכן אותה מתודה עובדת גם למספרים וגם למחרוזות.In max, the bound T extends Comparable<T> guarantees there's a compareTo, so the same method works for numbers and strings alike.
מתודות גנריות וגבולותGeneric methods and boundssum רק קוראת מספרים, ולכן `?sum only reads numbers, so `?
wildcards ו-PECSWildcards and PECSextends Number (מקבלת List<Integer> ו-List<Double>`).extends Number (it accepts List<Integer> and List<Double>`).
wildcards ו-PECSWildcards and PECSaddNumbers רק כותבת Integer, ולכן `?addNumbers only writes Integers, so `?
wildcards ו-PECSWildcards and PECS`incompatible types:`incompatible types:
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java saysמדף, צעד 22: Shelf<T> גנריShelf, step 22: a generic Shelf<T>
הצעד של היום בפרויקט מדףToday's step in the Shelf projectמה מחזירה get() של Box<String>?What does get() of a Box<String> return?
Object, וצריך המרהObject, and you need a castStringStringTTBoxBox
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.StringString
נכון: T הוחלף ב-String.Right: T was replaced by String.למה List<int> לא מתקמפל?Why doesn't List<int> compile?
- כי פרמטר טיפוס חייב להיות טיפוס של עצם, כמו
IntegerBecause a type parameter must be an object type, like Integer - כי int איטיBecause int is slow
- כי צריך
List<Number>Because you need List<Number> - זה מתקמפלIt compiles
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.כי פרמטר טיפוס חייב להיות טיפוס של עצם, כמו IntegerBecause a type parameter must be an object type, like Integer
נכון.Right.מתודה רק מוסיפה מספרים שלמים לרשימה. איזה טיפוס פרמטר הכי גמיש?A method only adds whole numbers to a list. Which parameter type is most flexible?
List<? super Integer>List<? super Integer>List<? extends Integer>List<? extends Integer>List<Integer> בלבדOnly List<Integer>List<?>List<?>
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.List<? super Integer>List<? super Integer>
נכון: Consumer Super. מקבלת גם List<Number> וגם List<Object>.Right: Consumer Super. It accepts List<Number> and List<Object> too.זוגA pair
class Pair<A, B> עם first(), second(), swap() שמחזירה Pair<B, A> חדש, ו-toString (Dune, 1965).class Pair<A, B> with first(), second(), swap() returning a new Pair<B, A>, and a toString (Dune, 1965).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.ספירה גנריתA generic count
static <T> int count(List<T> list, T wanted) סופרת כמה איברים שווים (equals) ל-wanted.static <T> int count(List<T> list, T wanted) counts how many items equal (equals) wanted.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מינימום לכל טיפוסA minimum for any type
static <T extends Comparable<T>> T min(List<T> list).static <T extends Comparable<T>> T min(List<T> list).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: מספר ברשימת מחרוזותBug hunter: a number in a list of strings
- התוכנית לא מתקמפלת.The program doesn't compile.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.ממוצע לכל מספרAn average of any numbers
- `static double average(List<?`static double average(List<?
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנוWhat we learned
- מחלקה גנרית: מחלקה עם פרמטר טיפוס:generic class: A class with a type parameter:
T הוא פרמטר טיפוס.T is a type parameter.- בלי generics, מספר היה נכנס לרשימת מחרוזות ומפיל את התוכנית מאוחר יותר.Without generics, a number would get into a list of strings and crash the program later.
last עובדת לכל רשימה.last works for any list.sum רק קוראת מספרים, ולכן `?sum only reads numbers, so `?- `incompatible types:`incompatible types:
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.