מערכים ומערכים דו-ממדייםArrays & 2D arrays
יצירה, גישה ואורך, לולאות על מערכים, Arrays.toString ו-sort, ומערכים דו-ממדיים כמו לוח משחק.
Creating, accessing and length, looping over arrays, Arrays.toString and sort, and 2D arrays like a game board.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- מערך: שורה של תאים צמודים מאותו טיפוס, בגודל קבוע:
int[] a = new int[5];אוint[] a = {1, 2, 3};. המערך הוא עצם ב-heap.array: A row of cells of the same type, with a fixed size:int[] a = new int[5];orint[] a = {1, 2, 3};. The array is an object on the heap. - length: מספר התאים במערך:
a.length(בלי סוגריים, בשונה מ-length()של String). האינדקס האחרון הואa.length - 1.length: The number of cells in an array:a.length(no brackets, unlike String'slength()). The last index isa.length - 1. - שתי הפניות לאותו עצם:
int[] b = a;לא מעתיק את המערך:bמצביע על אותו מערך. שינוי דרךbנראה גם דרךa. להעתקה:a.clone().aliasing:int[] b = a;doesn't copy the array:bpoints to the same array. A change throughbshows throughatoo. To copy:a.clone(). - מערך דו-ממדי: מערך של מערכים:
int[][] grid = new int[3][4];הוא 3 שורות ו-4 עמודות.grid[r][c]הוא תא.2D array: An array of arrays:int[][] grid = new int[3][4];is 3 rows and 4 columns.grid[r][c]is one cell. - ArrayIndexOutOfBoundsException: החריגה כשפונים לתא שלא קיים:
Index 5 out of bounds for length 3.ArrayIndexOutOfBoundsException: The exception for a cell that doesn't exist:Index 5 out of bounds for length 3.
02יצירה, אינדקס ו-lengthCreating, indexing and length
מערך בגודל קבוע. התא הראשון באינדקס 0 והאחרון ב-length - 1. מערך חדש של מספרים מתחיל באפסים.
An array has a fixed size. The first cell is index 0 and the last is length - 1. A new number array starts full of zeros.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = {90, 75, 88};
System.out.println(scores[0]);
scores[1] = 80;
System.out.println(scores.length);
int[] empty = new int[3];
System.out.println(Arrays.toString(scores) + " " + Arrays.toString(empty));
}
}90 3 [90, 80, 88] [0, 0, 0]
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03לולאות על מערך: סכום ומקסימוםLooping over an array: sum and max
for רגיל כשצריך את האינדקס, for-each כשצריך רק את הערכים. למקסימום מתחילים מהתא הראשון.
A plain for when you need the index, a for-each when you only need the values. For a maximum, start from the first cell.
public class Main {
public static void main(String[] args) {
int[] t = {21, 25, 19, 30};
int sum = 0;
for (int x : t) {
sum += x;
}
int max = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] > max) {
max = t[i];
}
}
System.out.println(sum + " " + max);
}
}95 30
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04שני משתנים, מערך אחדTwo variables, one array
b = a מעתיק את ההפניה, לא את המערך: שניהם מצביעים לאותו עצם (שתי הפניות לאותו עצם). clone() יוצר מערך חדש. צפו בזיכרון: b מצביע לאותו # כמו a, ו-c לעצם אחר.
b = a copies the reference, not the array: both point to the same object (aliasing). clone() makes a new array. Watch the memory: b points to the same # as a, and c to another object.
public class Main {
public static void main(String[] args) {
int[] a = {5, 6, 7};
int[] b = a;
b[0] = 50;
int[] c = a.clone();
c[1] = 60;
System.out.println(a[0] + " " + a[1]);
}
}50 6
צפו בהרצה צעד אחר צעד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
05מיון ומערך דו-ממדיSorting and a 2D array
Arrays.sort ממיין במקום. מערך דו-ממדי הוא מערך של שורות: grid[r][c].
Arrays.sort sorts in place. A 2D array is an array of rows: grid[r][c].
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] n = {4, 1, 3};
Arrays.sort(n);
System.out.println(Arrays.toString(n));
char[][] board = new char[2][3];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
board[r][c] = (r + c) % 2 == 0 ? 'X' : 'O';
}
System.out.println(new String(board[r]));
}
}
}[1, 3, 4] XOX OXO
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06טעויות נפוצות, ומה 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: past the edge
public class Main {
public static void main(String[] args) {
int[] a = {10, 20, 30};
int sum = 0;
for (int i = 0; i <= a.length; i++) {
sum += a[i];
}
System.out.println(sum);
}
}Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at Main.main(Main.java:6)
Index 3 out of bounds for length 3: ב-i <= a.length הלולאה מגיעה ל-i = 3, אבל האינדקס האחרון הוא 2. מתקנים ל-i < a.length.Index 3 out of bounds for length 3: with i <= a.length the loop reaches i = 3, but the last index is 2. Fix it to i < a.length.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
07הצעד של היום בפרויקט מדףToday's step in the Shelf project
מערך String[] titles = {"Emma", "Dune", "Ulysses", "Beloved"} ומערך int[] years = {1815, 1965, 1922, 1987}. הדפיסו את הספר הישן ביותר (Oldest: Emma (1815)), ואת השמות ממוינים לפי א-ב (Arrays.sort על עותק).
An array String[] titles = {"Emma", "Dune", "Ulysses", "Beloved"} and int[] years = {1815, 1965, 1922, 1987}. Print the oldest book (Oldest: Emma (1815)), and the titles sorted alphabetically (Arrays.sort on a copy).
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.