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

JavaJava
25
חלקPart 5: Java מודרנית וכליםModern Java & tools כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Collections לעומקCollections in depth

List, Set, Map ו-Queue, מימושים שונים, סיבוכיות זמן, ומתי לבחור מה.

List, Set, Map and Queue, different implementations, time complexity, and when to choose which.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • סיבוכיות (O גדול): כמה העבודה גדלה כשהאוסף גדל. contains ב-ArrayList הוא O(n) (עובר על הכול), ב-HashSet O(1) בממוצע, וב-TreeSet O(log n).complexity (big O): How the work grows as the collection grows. contains on an ArrayList is O(n) (it scans everything), on a HashSet O(1) on average, and on a TreeSet O(log n).
  • LinkedHashSet: Set ששומר את סדר ההכנסה. מהיר כמו HashSet.LinkedHashSet: A Set that keeps insertion order. As fast as a HashSet.
  • TreeSet: Set ממוין תמיד (לפי Comparable או Comparator), עם ניווט: floor, ceiling, subSet.TreeSet: An always-sorted Set (by Comparable or a Comparator), with navigation: floor, ceiling, subSet.
  • TreeMap: Map עם מפתחות ממוינים: firstKey, lastEntry, headMap(k) (כל מה שקטן מ-k).TreeMap: A Map with sorted keys: firstKey, lastEntry, headMap(k) (everything smaller than k).
  • ArrayDeque: תור דו-כיווני מהיר. כתור: offer ו-poll (ראשון נכנס, ראשון יוצא). כמחסנית: push ו-pop (אחרון נכנס, ראשון יוצא).ArrayDeque: A fast double-ended queue. As a queue: offer and poll (first in, first out). As a stack: push and pop (last in, first out).
  • PriorityQueue: תור ש-poll שלו מחזיר תמיד את האיבר הקטן ביותר (לפי הסדר הטבעי או Comparator), לא את הראשון שנכנס.PriorityQueue: A queue whose poll always returns the smallest item (by natural order or a Comparator), not the first one in.
  • Iterator: עצם שעובר על אוסף: hasNext(), next(), ו-remove() שמוחק בבטחה את האיבר האחרון שהוחזר.Iterator: An object that walks a collection: hasNext(), next(), and remove() which safely deletes the last item returned.

02שלושה Sets, שלושה סדריםThree Sets, three orders

שני ה-Sets מוחקים כפולים (fig מופיע פעם אחת). LinkedHashSet שומר את סדר ההכנסה, ו-TreeSet ממיין. (HashSet רגיל לא מבטיח שום סדר.)

Both Sets drop duplicates (fig appears once). LinkedHashSet keeps insertion order, and TreeSet sorts. (A plain HashSet promises no order at all.)

Main.java
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of("pear", "fig", "apple", "fig", "kiwi");
        Set<String> linked = new LinkedHashSet<>(words);
        Set<String> tree = new TreeSet<>(words);
        System.out.println(words.size() + " " + linked.size());
        System.out.println(linked);
        System.out.println(tree);
        System.out.println(tree.contains("kiwi"));
    }
}
פלטOutput
5 4
[pear, fig, apple, kiwi]
[apple, fig, kiwi, pear]
true
צפו בהרצה צעד אחר צעד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

03TreeMap: מפתחות ממוינים וניווטTreeMap: sorted keys and navigation

TreeMap מחזיק את השנים ממוינות. headMap(1950) נותן את כל מה שלפני 1950, ו-ceilingKey(1900) את המפתח הראשון שגדול או שווה ל-1900.

A TreeMap keeps the years sorted. headMap(1950) gives everything before 1950, and ceilingKey(1900) the first key at or above 1900.

Main.java
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<Integer, String> byYear = new TreeMap<>();
        byYear.put(1965, "Dune");
        byYear.put(1815, "Emma");
        byYear.put(1922, "Ulysses");
        System.out.println(byYear);
        System.out.println(byYear.firstKey() + " " + byYear.lastEntry().getValue());
        System.out.println(byYear.headMap(1950));
        System.out.println(byYear.ceilingKey(1900));
    }
}
פלטOutput
{1815=Emma, 1922=Ulysses, 1965=Dune}
1815 Dune
{1815=Emma, 1922=Ulysses}
1922
צפו בהרצה צעד אחר צעד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תור, מחסנית ותור עדיפויותQueue, stack and priority queue

אותו ArrayDeque משמש כתור (offer/poll) וכמחסנית (push/pop). PriorityQueue מוציא תמיד את הקטן ביותר.

The same ArrayDeque serves as a queue (offer/poll) and a stack (push/pop). A PriorityQueue always takes out the smallest.

Main.java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        Deque<String> queue = new ArrayDeque<>();
        queue.offer("Noa");
        queue.offer("Avi");
        queue.offer("Dana");
        System.out.println(queue.poll() + " is served, next " + queue.peek());
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop() + " " + stack.pop());
        PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(5, 1, 4));
        System.out.println(pq.poll() + " " + pq.poll());
    }
}
פלטOutput
Noa is served, next Avi
3 2
1 4
צפו בהרצה צעד אחר צעד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

05טעויות נפוצות, ומה 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.List;

public class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>(List.of("a", "tree", "is", "green"));
        for (String w : words) {
            if (w.length() < 3) {
                words.remove(w);
            }
        }
        System.out.println(words);
    }
}
מה 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:7)
בעברית פשוטה: In plain words: java.util.ConcurrentModificationException: for-each משתמש ב-Iterator בסתר, ו-words.remove משנה את הרשימה מאחורי הגב שלו.java.util.ConcurrentModificationException: a for-each uses an Iterator behind the scenes, and words.remove changes the list behind its back.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

06הצעד של היום בפרויקט מדףToday's step in the Shelf project

Index מחזיק שתי מפות: סופר → רשימת כותרים (TreeMap<String, List<String>>), וז'אנר → כותרים ממוינים (TreeMap<String, Set<String>>). add, byAuthor ו-byGenre (רשימה ריקה כשאין). הדפיסו [Emma, Persuasion], [Children of Dune, Dune], [].

Index holds two maps: author → list of titles (TreeMap<String, List<String>>), and genre → sorted titles (TreeMap<String, Set<String>>). add, byAuthor and byGenre (empty when missing). Print [Emma, Persuasion], [Children of Dune, Dune], [].

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