ArrayList: a list that grows · ArrayList: רשימה הצומחת
A list that can grow
- An array has a fixed size. Once you make it, the length cannot change.
- An
ArrayListis a list that can grow and shrink while the program runs. - You must import it at the top of the file:
import java.util.ArrayList;.
רשימה שניתן לגדול
- למערכת יש גודל קבוע. ברגע שנוצרת אותה, האורך לא יכול להשתנות.
ArrayListהיא רשימה שניתן לגדול ולהתכווץ בזמן הפעלת התוכנה.- עליך לייצא אותה בראש הקובץ:
import java.util.ArrayList;.
Making an ArrayList
- Write the type of the items inside
<...>. This is the AP CSA way. ArrayList<String>holds text.ArrayList<Integer>holds whole numbers.- A new list starts empty, with size
0.
יצירת ArrayList
- כתוב את סוג הפריטים בתוך
<...>. זו הדרך המקובלת ב-AP CSA. ArrayList<String>מחזיק טקסט.ArrayList<Integer>מחזיק מספרים שלמים.- רשימה חדשה מתחילה רוקה, בגודל
0.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
System.out.println(names.size()); // 0
names.add("Ann");
names.add("Bo");
System.out.println(names.size()); // 2
System.out.println(names); // [Ann, Bo]
}
}
The five methods you need
list.size()— how many items are in the list.list.add(x)— putxat the end of the list.list.get(i)— the item at positioni(the first position is 0).list.set(i, x)— replace the item at positioniwithx.list.remove(i)— take out the item at positioni; later items shift left.
חמישית השיטות שאתה צריך
list.size()— כמה פריטים יש ברשימה.list.add(x)— הוסףxבסוף הרשימה.list.get(i)— האלמנט במיקוםi(המיקום הראשון הוא 0).list.set(i, x)— החלף את הפריט במיקוםiב-x.list.remove(i)— הסר את הפריט במיקוםi; הפריטים הבאים יזוזו שמאלה.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> fruit = new ArrayList<String>();
fruit.add("apple");
fruit.add("pear");
fruit.add("plum");
System.out.println(fruit.get(0)); // apple
fruit.set(1, "grape"); // pear -> grape
fruit.remove(2); // take out "plum"
System.out.println(fruit); // [apple, grape]
}
}
Numbers need Integer
- An
ArrayListcan only hold objects, not the simple typeint. - So we write
ArrayList<Integer>.Integeris the object form ofint. - Java changes between
intandIntegerfor you. This is called autoboxing. - You can
add(7)anint, andget(0)gives back a value you can use asint.
למספרים נדרש Integer
ArrayListיכול להכיל רק אובייקטים, לא את סוג הפשוטint.- לכן אנחנו כותבים
ArrayList<Integer>.Integerהוא הצורה האובייקטיבית שלint. - Java מעבירה בין
intל-Integerעבורך. תהליך זה נקרא Autoboxing (אוטובוקסינג). - ניתן ל-
add(7)אובייקטint, וה-get(0)מחזיר ערך שיכול לשמש כ-int.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(10); // int 10 is boxed into Integer
nums.add(20);
int first = nums.get(0); // unboxed back to int
System.out.println(first + nums.get(1)); // 30
}
}
Two ways to traverse
- An index for-loop uses positions
0tosize() - 1. Use it when you need the index. - An enhanced for-loop (
for (int x : list)) reads each item in turn. Use it when you only need the values. - Both visit every item once, in order.
שתי דרכים לעבור על רשימה
- לולאת for עם אינדקס משתמשת במיקומים מ-
0עדsize() - 1. השתמש בה כאשר אתה זקוק לאינדקס. - לולאת for מוגברת (
for (int x : list)) קוראת כל פריט בתור. השתמש בה כאשר אתה זקוק רק לערכים. - שתיהן מבקרות בכל פריט פעם אחת, בסדר.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(5);
nums.add(8);
// index for-loop
for (int i = 0; i < nums.size(); i++) {
System.out.println("at " + i + ": " + nums.get(i));
}
// enhanced for-loop
int total = 0;
for (int x : nums) {
total = total + x;
}
System.out.println("total " + total); // total 16
}
}
Common mistakes
ArrayListuses.add,.get(i),.size()— not[].- Store objects: use
ArrayList<Integer>, notArrayList<int>.
טעויות נפוצות
ArrayListמשתמש ב-.add,.get(i),.size()— ולא ב-[].- לאחסון אובייקטים: השתמש ב-
ArrayList<Integer>, ולא ב-ArrayList<int>.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
כעת תנסו בעצמכם
- כל משימה ממלאת מראש את שלד המחלקה — כתוב את הקוד שלך בתוך main, או השלם את השיטה המוצגת.
- לחץ על Run כדי להרכיב ולהריץ, ולאחר מכן לחץ על Check answer.
- הקוד שלך נרכב ונרץ על השרת, ולכן גם ההפעלה הראשונה היא מהירה.
An ArrayList grows · ArrayList צומחת
Unlike an array, an ArrayList changes size as you add/remove. · בניגוד למערץ, ל-ArrayList מתחלפת אורך כשמוסיפים או מורידים ממנה.
Complete sumList(ArrayList<Integer> a) so it returns the total of all numbers in the list. An empty list totals 0. Traverse with a loop. · השלם sumList(ArrayList<Integer> a) כך שיחזיר את סך הכל של כל המספרים ברשימה. רשימה ריקה סך הכל היא 0. טפל בה באמצעות לולאה.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete countUp(int n) so it makes a new ArrayList<Integer>, adds the numbers 1, 2, ..., n in order, and returns it. If n is 0, return an empty list. · השלם countUp(int n) כך שיצור חדש ArrayList<Integer>, יוסיף את המספרים 1, 2, ..., n בסדר, ויחזיר אותו. אם n הוא 0, החזר רשימה ריקה.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete doubleAt(ArrayList<Integer> a, int i). Read the value at index i with get, then use set to store two times that value back at index i. Return nothing (void). · השלם doubleAt(ArrayList<Integer> a, int i). קרא את הערך באינדקס i באמצעות get, ואז השתמש בset כדי לאחסן פי שניים מהערך הזה בחזרה באינדקס i. אל תחזיר דבר (void).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.