Vâng đây là mẹo.
Hãy lấy hai ví dụ ở đây:
public class ArrayListExample {
public static void main(String[] args) {
Collection<Integer> collection = new ArrayList<>();
List<Integer> arrayList = new ArrayList<>();
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(null);
collection.add(4);
collection.add(null);
System.out.println("Collection" + collection);
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(null);
arrayList.add(4);
arrayList.add(null);
System.out.println("ArrayList" + arrayList);
collection.remove(3);
arrayList.remove(3);
System.out.println("");
System.out.println("After Removal of '3' :");
System.out.println("Collection" + collection);
System.out.println("ArrayList" + arrayList);
collection.remove(null);
arrayList.remove(null);
System.out.println("");
System.out.println("After Removal of 'null': ");
System.out.println("Collection" + collection);
System.out.println("ArrayList" + arrayList);
}
}
Bây giờ hãy xem đầu ra:
Collection[1, 2, 3, null, 4, null]
ArrayList[1, 2, 3, null, 4, null]
After Removal of '3' :
Collection[1, 2, null, 4, null]
ArrayList[1, 2, 3, 4, null]
After Removal of 'null':
Collection[1, 2, 4, null]
ArrayList[1, 2, 3, 4]
Bây giờ hãy phân tích đầu ra:
Khi 3 được xóa khỏi bộ sưu tập, nó gọi remove()phương thức của bộ sưu tập lấy Object otham số. Do đó nó loại bỏ các đối tượng 3. Nhưng trong đối tượng ArrayList, nó bị ghi đè bởi chỉ số 3 và do đó phần tử thứ 4 bị loại bỏ.
Theo cùng một logic của việc loại bỏ đối tượng null được loại bỏ trong cả hai trường hợp ở đầu ra thứ hai.
Vì vậy, để loại bỏ số 3đó là một đối tượng, chúng ta sẽ cần phải vượt qua 3 như một object.
Và điều đó có thể được thực hiện bằng cách đúc hoặc gói bằng cách sử dụng lớp bao bọc Integer.
Ví dụ:
Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);