ArrayList algorithms: filter and the remove bug · Algoritma ArrayList: filter dan bug penghapusan
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.
Melakukan pekerjaan pada seluruh daftar
- Sekarang Anda dapat menyimpan data dalam an
ArrayList. Selanjutnya kita proses data tersebut. - Pekerjaan umum: hitung item yang sesuai aturan, filter mereka ke dalam daftar baru, dan hapus sebagian darinya.
- Semua ini menggunakan loop atas daftar.
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.
Menghitung dengan aturan
- Lintasi daftar, uji setiap item, dan tambahkan
1ke penghitung ketika uji berhasil. n % 2 == 0bernilai benar jikangenap.n % 2 != 0bernilai benar jikanganjil.- Ini hanya membaca daftar, jadi enhanced for-loop sudah cukup.
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.
Memfilter ke daftar baru
- Filtering hanya menyimpan item yang lolos uji.
- Pola yang aman: buat daftar baru kosong, lalu
addsetiap item yang lolos. - Daftar lama tidak berubah. Ini menghindari bug yang akan kita lihat selanjutnya.
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.
Bug remove-while-iterating
- Tampaknya mudah: loop maju dan
remove(i)item-item yang tidak diinginkan. - Namun,
remove(i)menggeser setiap item berikutnya satu posisi ke kiri. Loop kemudian menambahkan1keidan melewati item yang berpindah ke posisi lama. - Contoh di bawah mencoba menghapus semua genap tetapi melewatkan satu.
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.
Mengapa melewatkan
- Mulai:
[2, 4, 5],i = 0.2genap, hapus. Daftar menjadi[4, 5]. - The
4turun ke index0. Tapi loop sekarang mengaturi = 1. - Di
i = 1kita melihat5, bukan4. The4tidak pernah diperiksa. Ia tetap ada.
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.
Perbaikan: loop mundur
- Lintasi dari index terakhir turun ke
0. - Ketika Anda menghapus index
i, hanya item-item setelahiyang bergeser — dan Anda telah melewati item-item tersebut. - Indeks yang masih perlu dikunjungi adalah lebih kecil dari
i, jadi tidak ada yang bergerak menjauh dari Anda.
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.
Catatan tentang enhanced for-loop
- Anda mungkin tergoda untuk menghapus di dalam
for (int x : nums). - Jangan lakukan. Mengubah ukuran daftar selama enhanced for-loop menyebabkan
ConcurrentModificationExceptiondan menghentikan program. - Untuk menghapus, selalu gunakan loop indeks mundur di atas.
Common mistakes
- Removing while looping forward by index skips the next item (the remove bug).
- Loop backwards, or use an iterator, when removing.
Kesalahan umum
- Menghapus saat looping maju berdasarkan indeks melewatkan item berikutnya (bug remove).
- Loop mundur, atau gunakan iterator, saat menghapus.
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.
Sekarang Anda coba
- Setiap tugas telah mengisi kerangka class — tulis kode Anda di dalam main, atau lengkapi method yang ditampilkan.
- Tekan Jalankan untuk mengompilasi dan menjalankan, lalu Periksa jawaban.
- Kode Anda dikompilasi dan dijalankan di server, sehingga bahkan jalankan pertama kali pun cepat.
Filtering a list · Memfilter daftar
Removing while looping shifts indices — step through to see why. · Menghapus saat perulangan menggeser indeks — telusuri untuk melihat alasannya.
Complete countOdds(ArrayList<Integer> a) so it returns how many numbers in the list are odd. A number is odd when x % 2 != 0. · Lengkapi countOdds(ArrayList<Integer> a) agar mengembalikan berapa banyak angka dalam daftar yang ganjil. Suatu angka adalah ganjil ketika x % 2 != 0.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
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. · Lengkapi keepPositives(ArrayList<Integer> a). Bangun dan kembalikan ArrayList<Integer> baru yang hanya berisi angka-angka yang lebih besar dari 0, dalam urutan aslinya. Jangan ubah a.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
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). · Lengkapi removeEvens(ArrayList<Integer> a) agar menghapus setiap angka genap dari a itu sendiri. Loop mundur berdasarkan indeks agar Anda tidak melewatkan item. Kembalikan sesuatu (void).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.