GenericsGenerics
מחלקות ומתודות גנריות, bounded types, wildcards ו-PECS, ו-type erasure.
Generic classes and methods, bounded types, wildcards and PECS, and type erasure.
זוגA pair
תזכורת: מה ביקשוReminder: the task
class Pair<A, B> עם first(), second(), swap() שמחזירה Pair<B, A> חדש, ו-toString (Dune, 1965). הדפיסו (Dune, 1965) (1965, Dune) ואז 1966 (q.first() + 1, בלי המרה).
class Pair<A, B> with first(), second(), swap() returning a new Pair<B, A>, and a toString (Dune, 1965). Print (Dune, 1965) (1965, Dune) then 1966 (q.first() + 1, with no cast).
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
Pair<String, Integer> p = new Pair<>("Dune", 1965);
Pair<Integer, String> q = p.swap();
System.out.println(p + " " + q);
System.out.println(q.first() + 1);
}
}
class Pair<A, B> {
private final A first;
private final B second;
Pair(A first, B second) {
this.first = first;
this.second = second;
}
A first() {
return first;
}
B second() {
return second;
}
Pair<B, A> swap() {
return new Pair<>(second, first);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}(Dune, 1965) (1965, Dune) 1966
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ספירה גנריתA generic count
תזכורת: מה ביקשוReminder: the task
static <T> int count(List<T> list, T wanted) סופרת כמה איברים שווים (equals) ל-wanted. הדפיסו 3 עבור a ברשימה a, b, a, a, ו-2 עבור 2 ב-1, 2, 2.
static <T> int count(List<T> list, T wanted) counts how many items equal (equals) wanted. Print 3 for a in a, b, a, a, and 2 for 2 in 1, 2, 2.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
public class Main {
static <T> int count(List<T> list, T wanted) {
int n = 0;
for (T x : list) {
if (x.equals(wanted)) {
n++;
}
}
return n;
}
public static void main(String[] args) {
System.out.println(count(List.of("a", "b", "a", "a"), "a"));
System.out.println(count(List.of(1, 2, 2), 2));
}
}3 2
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מינימום לכל טיפוסA minimum for any type
תזכורת: מה ביקשוReminder: the task
static <T extends Comparable<T>> T min(List<T> list). הדפיסו 3 עבור 7, 3, 9, ו-apple עבור pear, apple, fig.
static <T extends Comparable<T>> T min(List<T> list). Print 3 for 7, 3, 9, and apple for pear, apple, fig.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
public class Main {
static <T extends Comparable<T>> T min(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(min(List.of(7, 3, 9)));
System.out.println(min(List.of("pear", "apple", "fig")));
}
}3 apple
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: מספר ברשימת מחרוזותBug hunter: a number in a list of strings
תזכורת: מה ביקשוReminder: the task
התוכנית לא מתקמפלת. הכניסו את השנה כמחרוזת (String.valueOf) כך שיודפס [Dune, 1965].
The program doesn't compile. Put the year in as a string (String.valueOf) so it prints [Dune, 1965].
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
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(String.valueOf(1965));
System.out.println(labels);
}
}[Dune, 1965]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ממוצע לכל מספרAn average of any numbers
תזכורת: מה ביקשוReminder: the task
static double average(List<? extends Number> nums) עובדת גם עם List<Integer> וגם עם List<Double>. הדפיסו 5.0 2.0.
static double average(List<? extends Number> nums) works with a List<Integer> and a List<Double> alike. Print 5.0 2.0.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
public class Main {
static double average(List<? extends Number> nums) {
double sum = 0;
for (Number n : nums) {
sum += n.doubleValue();
}
return sum / nums.size();
}
public static void main(String[] args) {
List<Integer> ints = List.of(2, 4, 9);
List<Double> doubles = List.of(1.5, 2.5);
System.out.println(average(ints) + " " + average(doubles));
}
}5.0 2.0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 22: Shelf<T> גנריShelf, step 22: a generic Shelf<T>
תזכורת: מה ביקשוReminder: the task
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).
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Shelf<String> titles = new Shelf<>("titles");
titles.add("Dune");
titles.add("Emma");
Shelf<Integer> years = new Shelf<>("years");
years.add(1965);
years.add(1815);
System.out.println(titles + " " + years);
String first = titles.get(0);
int sum = years.get(0) + years.get(1);
System.out.println(first + " " + sum);
}
}
class Shelf<T> {
private final String name;
private final List<T> items = new ArrayList<>();
Shelf(String name) {
this.name = name;
}
void add(T item) {
items.add(item);
}
T get(int i) {
return items.get(i);
}
int size() {
return items.size();
}
@Override
public String toString() {
return name + items;
}
}titles[Dune, Emma] years[1965, 1815] Dune 3780
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
העתקה לפי PECSCopying by PECS
תזכורת: מה ביקשוReminder: the task
static <T> void copy(List<? extends T> src, List<? super T> dst) מעתיקה הכול מ-src ל-dst. העתיקו List<Integer> ו-List<Double> ל-List<Number>, ואת זו ל-List<Object>. הדפיסו [1, 2, 3.5] 3.
static <T> void copy(List<? extends T> src, List<? super T> dst) copies everything from src to dst. Copy a List<Integer> and a List<Double> into a List<Number>, and that into a List<Object>. Print [1, 2, 3.5] 3.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
public class Main {
static <T> void copy(List<? extends T> src, List<? super T> dst) {
for (T x : src) {
dst.add(x);
}
}
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2);
List<Double> doubles = List.of(3.5);
List<Number> all = new ArrayList<>();
copy(ints, all);
copy(doubles, all);
List<Object> objects = new ArrayList<>();
copy(all, objects);
System.out.println(all + " " + objects.size());
}
}[1, 2, 3.5] 3
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מונה גנריA generic counter
תזכורת: מה ביקשוReminder: the task
class Counter<T> עם add(T), count(T) ו-T top() (הנפוץ ביותר). ספרו את המילים של to be or not to be to והדפיסו to 3 0, ואחר כך את הקובייה הנפוצה מ-3, 6, 6, 1: 6.
class Counter<T> with add(T), count(T) and T top() (the most common). Count the words of to be or not to be to and print to 3 0, then the most common die from 3, 6, 6, 1: 6.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Counter<String> words = new Counter<>();
for (String w : "to be or not to be to".split(" ")) {
words.add(w);
}
System.out.println(words.top() + " " + words.count("to") + " " + words.count("xyz"));
Counter<Integer> dice = new Counter<>();
for (int d : List.of(3, 6, 6, 1)) {
dice.add(d);
}
System.out.println(dice.top());
}
}
class Counter<T> {
private final Map<T, Integer> counts = new HashMap<>();
void add(T item) {
counts.put(item, counts.getOrDefault(item, 0) + 1);
}
int count(T item) {
return counts.getOrDefault(item, 0);
}
T top() {
T best = null;
for (Map.Entry<T, Integer> e : counts.entrySet()) {
if (best == null || e.getValue() > counts.get(best)) {
best = e.getKey();
}
}
return best;
}
}to 3 0 6
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.