ArrayList algorithms: filter and the remove bug · خوارزميات ArrayList: التصفية وخطأ الإزالة
Doing work on a whole list
- Now you can store data in an
ArrayList. Next we process it. - Common jobs: count items that match a rule, filter them into a new list, and remove some of them.
- All of these use a loop over the list.
إجراء عمل على قائمة كاملة
- الآن يمكنك تخزين البيانات في
ArrayList.下一步 نحن نعالجها. - مهام شائعة: عدّ العناصر المطابقة لقاعدة، تصفيتها في قائمة جديدة، وإزالة بعضها.
- جميعها تستخدم تكرارًا عبر القائمة.
Counting with a rule
- Walk the list, test each item, and add
1to a counter when the test is true. n % 2 == 0is true whennis even.n % 2 != 0is true whennis odd.- This only reads the list, so an enhanced for-loop is fine.
العد بقاعدة
- مرر القائمة، اختبر كل عنصر، وأضف
1للعداد عندما يكون الاختبار صحيحًا. n % 2 == 0تكون صحيحة عندماnزوجي.n % 2 != 0تكون صحيحة عندماnفردي.- هذا يقرأ القائمة فقط، لذا فإن حلقة for المحسّنة كافية.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(4);
nums.add(7);
nums.add(10);
nums.add(3);
int evens = 0;
for (int x : nums) {
if (x % 2 == 0) {
evens = evens + 1;
}
}
System.out.println(evens); // 2
}
}
Filtering into a new list
- Filtering keeps only the items that pass a test.
- A safe pattern: make an empty new list, then
addeach item that passes. - The old list is not changed. This avoids the bug we see next.
التصفية في قائمة جديدة
- التصفية تحتفظ بالعناصر التي تمر اختبارًا فقط.
- نمط آمن: قم بإنشاء قائمة جديدة فارغة، ثم
addلكل عنصر يمر. - القائمة القديمة غير معدّلة. هذا يتجنب الخطأ الذي سنراه لاحقًا.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(4);
nums.add(7);
nums.add(10);
nums.add(3);
ArrayList<Integer> bigOnes = new ArrayList<Integer>();
for (int x : nums) {
if (x >= 5) {
bigOnes.add(x);
}
}
System.out.println(bigOnes); // [7, 10]
}
}
The remove-while-iterating bug
- It looks easy: loop forward and
remove(i)the items you do not want. - But
remove(i)shifts every later item one place left. The loop then adds1toiand skips the item that moved into the old spot. - The example below tries to remove all evens but misses one.
خطأ إزالة أثناء التكرار
- يبدو الأمر سهلاً: كرر للأمام و
remove(i)للعناصر التي لا تريدها. - لكن
remove(i)ينزح كل عنصر لاحق مكانًا واحدًا لليسار. ثم تضيف الحلقة1إلىiوتتخطّى العنصر الذي انتقل إلى المكان القديم. - المثال أدناه يحاول إزالة كل الأعداد الزوجية لكنه يفوت واحداً.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(2);
nums.add(4); // this one gets skipped!
nums.add(5);
// BUGGY: forward loop while removing
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) % 2 == 0) {
nums.remove(i);
}
}
System.out.println(nums); // [4, 5] -- wrong, 4 was missed
}
}
Why it skips
- Start:
[2, 4, 5],i = 0.2is even, remove it. List becomes[4, 5]. - The
4slid down into index0. But the loop now setsi = 1. - At
i = 1we look at5, not4. The4was never checked. It stays in.
لماذا يتخطى
- البداية:
[2, 4, 5]،i = 0.2زوجي، أزلها. تصبح القائمة[4, 5]. - انزلق
4للأسفل إلى الفهرس0. لكن الحلقة تضبط الآنi = 1. - عند
i = 1ننظر إلى5، وليس4. لم يتم فحص4أبدًا. يبقى في القائمة.
The fix: loop backwards
- Walk from the last index down to
0. - When you remove index
i, only items afterishift — and you have already passed those. - The indexes you still need to visit are smaller than
i, so nothing moves out from under you.
الحل: التكرار العكسي
- مرر من آخر فهرس نزولاً إلى
0. - عند إزالة الفهرس
i، تنزح العناصر بعدiفقط — وقد مررت بها بالفعل. - الفهارس التي لا تزال بحاجة لزيارتها أصغر من
i، لذا لا شيء يتحرك من تحتك.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(2);
nums.add(4);
nums.add(5);
// SAFE: backward loop while removing
for (int i = nums.size() - 1; i >= 0; i--) {
if (nums.get(i) % 2 == 0) {
nums.remove(i);
}
}
System.out.println(nums); // [5] -- correct
}
}
A note on the enhanced for-loop
- You may be tempted to remove inside
for (int x : nums). - Do not. Changing the list size during an enhanced for-loop throws a
ConcurrentModificationExceptionand stops the program. - For removing, always use the backward index loop above.
ملاحظة حول حلقة for المحسّنة
- قد تغري نفسك بإزالة عناصر داخل
for (int x : nums). - لا تفعل ذلك. تغيير حجم القائمة أثناء حلقة for المحسّنة يرمي
ConcurrentModificationExceptionويوقف البرنامج. - للإزالة، استخدم دائمًا حلقة المؤشر العكسية أعلاه.
Common mistakes
- Removing while looping forward by index skips the next item (the remove bug).
- Loop backwards, or use an iterator, when removing.
أخطاء شائعة
- الإزالة أثناء التكرار للأمام بالمؤشر تتخطى العنصر التالي (خطأ الإزالة).
- كرر للخلف، أو استخدم مُمرِّر (iterator)، عند الإزالة.
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، أو أكمل الدالة المعروضة.
- اضغط تشغيل للمعالجة والتشغيل، ثم تحقق من الإجابة.
- كودك يُعالج ويُشغل على الخادم، لذا حتى التشغيل الأول سريع.
Filtering a list · تصفية قائمة
Removing while looping shifts indices — step through to see why. · الإزالة أثناء التمرير يحرك الفهارس — مرر خطوة بخطوة لترى السبب.
Complete countOdds(ArrayList<Integer> a) so it returns how many numbers in the list are odd. A number is odd when x % 2 != 0. · أكمل countOdds(ArrayList<Integer> a) لتُرجع عدد الأرقام الزوجية في القائمة. يكون الرقم فرديًا عندما x % 2 != 0.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Complete keepPositives(ArrayList<Integer> a). Build and return a new ArrayList<Integer> that holds only the numbers greater than 0, in their original order. Do not change a. · أكمل keepPositives(ArrayList<Integer> a). أنشئ وأرجع ArrayList<Integer> جديدًا يحتوي فقط على الأرقام الأكبر من 0، بنفس ترتيبها الأصلي. لا تُغير a.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Complete removeEvens(ArrayList<Integer> a) so it removes every even number from a itself. Loop backwards by index so you do not skip items. Return nothing (void). · أكمل removeEvens(ArrayList<Integer> a) لإزالة كل عدد زوجي من a نفسه. مرر عكسياً بالفهرس حتى لا تتخطى عناصر. لا تُرجع شيئًا (void).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.