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

JavaJava
9
חלקPart 2: מתודות ומערכיםMethods & arrays כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

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. put with 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: Integer for int, Double for double. Collections hold only objects, hence List<Integer>.
  • autoboxing: Java הופכת לבד int ל-Integer כשמכניסים לאוסף, ובחזרה כשמוציאים.autoboxing: Java turns an int into an Integer by 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 <>.

Main.java
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"));
    }
}
פלטOutput
[Ulysses, Dune, Emma]
Dune 2 false
צפו בהרצה צעד אחר צעד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

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.

Main.java
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);
    }
}
פלטOutput
[5, 12, 7] sum 24
צפו בהרצה צעד אחר צעד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

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.

Main.java
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());
    }
}
פלטOutput
3
צפו בהרצה צעד אחר צעד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 visualizerרשימה היא עצם: שתי הפניותA list is an object: two references

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

Main.java
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());
    }
}
פלטOutput
896
null
0
true 2
צפו בהרצה צעד אחר צעד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ספירה עם מילון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.

Main.java
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);
    }
}
פלטOutput
{be=2, not=1, or=1, to=2}
צפו בהרצה צעד אחר צעד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

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.

טעות נפוצהCommon mistake

צייד באגים: מחיקה תוך כדי לולאה

Bug hunter: removing while looping

Main.java
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);
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
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)
בעברית פשוטה: In plain words: 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

טיפ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