ArrayList ו-HashMap ראשוניםFirst ArrayList & HashMap
רשימה שגדלה לבד, מילון של מפתח וערך, טיפוסים עטופים (Integer) ו-autoboxing.
A list that grows by itself, a key-value map, wrapper types (Integer) and autoboxing.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- ArrayList: רשימה שגדלה לבד:
List<String> l = new ArrayList<>();,l.add(x),l.get(i),l.size().ArrayList: A list that grows by itself:List<String> l = new ArrayList<>();,l.add(x),l.get(i),l.size(). - HashMap: מילון של מפתח וערך:
Map<String, Integer> m = new HashMap<>();,m.put(k, v),m.get(k). הסדר לא מובטח.HashMap: A key-value map:Map<String, Integer> m = new HashMap<>();,m.put(k, v),m.get(k). The order isn't guaranteed. - מפתח וערך: במילון כל מפתח מופיע פעם אחת, ולכל מפתח ערך אחד.
putעם מפתח קיים מחליף את הערך.key and value: In a map each key appears once, with one value.putwith an existing key replaces the value. - סוגריים משולשים <>: אומרים מה יש בתוך האוסף:
List<String>היא רשימה של מחרוזות. המהדר לא ייתן להכניס משהו אחר.angle brackets <>: They say what's inside the collection:List<String>is a list of strings. The compiler won't let anything else in. - טיפוס עוטף: גרסת עצם של טיפוס פרימיטיבי:
Integerל-int,Doubleל-double. אוספים מחזיקים רק עצמים, ולכןList<Integer>.wrapper type: The object version of a primitive type:Integerforint,Doublefordouble. Collections hold only objects, henceList<Integer>. - autoboxing: Java הופכת לבד
intל-Integerכשמכניסים לאוסף, ובחזרה כשמוציאים.autoboxing: Java turns anintinto anIntegerby itself when you put it in a collection, and back when you take it out.
02ArrayList: רשימה שגדלהArrayList: a list that grows
בניגוד למערך, ל-ArrayList אין גודל קבוע. add מוסיף לסוף, get(i) קורא, set מחליף, remove מוחק (והשאר זזים). הטיפוס בתוך <>.
Unlike an array, an ArrayList has no fixed size. add appends, get(i) reads, set replaces, remove deletes (and the rest shift). The type goes inside <>.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<String> books = new ArrayList<>();
books.add("Dune");
books.add("Emma");
books.add(0, "Ulysses");
System.out.println(books);
books.remove("Emma");
System.out.println(books.get(1) + " " + books.size() + " " + books.contains("Emma"));
}
}[Ulysses, Dune, Emma] Dune 2 false
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03רשימה של מספרים: Integer ו-autoboxingA list of numbers: Integer and autoboxing
אוספים מחזיקים רק עצמים, ולכן כותבים List<Integer>. autoboxing: Java ממירה בין int ל-Integer לבד.
Collections hold only objects, so you write List<Integer>. Autoboxing: Java converts between int and Integer by itself.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();
nums.add(5);
nums.add(12);
nums.add(7);
int total = 0;
for (int n : nums) {
total += n;
}
System.out.println(nums + " sum " + total);
}
}[5, 12, 7] sum 24
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04רשימה היא עצם: שתי הפניותA list is an object: two references
כמו במערך, same = names לא מעתיק את הרשימה: שתי הפניות לאותו עצם. בזיכרון רואים רשימה אחת ושני חצים.
As with arrays, same = names doesn't copy the list: two references to the same object. In memory you see one list and two arrows.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Noa");
names.add("Avi");
List<String> same = names;
same.add("Dana");
System.out.println(names.size());
}
}3
צפו בהרצה צעד אחר צעד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
05HashMap: מפתח וערךHashMap: key and value
HashMap ממפה מפתח לערך. put מוסיף או מחליף, get מחזיר (או null אם אין), ו-getOrDefault נותן ערך ברירת מחדל. הסדר של HashMap לא מובטח, ולכן בדוגמה מדפיסים לפי מפתח.
A HashMap maps a key to a value. put adds or replaces, get returns it (or null if missing), and getOrDefault gives a default. A HashMap's order isn't guaranteed, so the example prints by key.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> pages = new HashMap<>();
pages.put("Dune", 412);
pages.put("Emma", 474);
pages.put("Dune", 896);
System.out.println(pages.get("Dune"));
System.out.println(pages.get("Hamlet"));
System.out.println(pages.getOrDefault("Hamlet", 0));
System.out.println(pages.containsKey("Emma") + " " + pages.size());
}
}896 null 0 true 2
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06ספירה עם מילוןCounting with a map
התבנית הכי שימושית: לכל פריט, getOrDefault(x, 0) + 1. TreeMap שומר את המפתחות ממוינים, ולכן ההדפסה תמיד באותו סדר.
The most useful pattern: for each item, getOrDefault(x, 0) + 1. A TreeMap keeps its keys sorted, so printing is always in the same order.
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String text = "to be or not to be";
Map<String, Integer> count = new TreeMap<>();
for (String w : text.split(" ")) {
count.put(w, count.getOrDefault(w, 0) + 1);
}
System.out.println(count);
}
}{be=2, not=1, or=1, to=2}צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
07טעויות נפוצות, ומה 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: removing while looping
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(4, -2, 7, -5));
for (Integer n : nums) {
if (n < 0) {
nums.remove(n);
}
}
System.out.println(nums);
}
}Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1095) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1049) at Main.main(Main.java:9)
java.util.ConcurrentModificationException: אסור לשנות רשימה בזמן שלולאת for-each עוברת עליה. removeIf עושה את זה בבטחה.java.util.ConcurrentModificationException: you can't change a list while a for-each is going over it. removeIf does it safely.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
08הצעד של היום בפרויקט מדףToday's step in the Shelf project
שמרו את הספרים ב-List<String> בפורמט Title|Author: Dune|Herbert, Emma|Austen, Persuasion|Austen, Children of Dune|Herbert, Ulysses|Joyce. ספרו ב-TreeMap כמה ספרים יש לכל סופר והדפיסו Austen: 2 וכן הלאה, ובסוף Total: 5.
Keep the books in a List<String> as Title|Author: Dune|Herbert, Emma|Austen, Persuasion|Austen, Children of Dune|Herbert, Ulysses|Joyce. Count with a TreeMap how many books each author has and print Austen: 2 and so on, then Total: 5.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.