वैसे यहाँ चाल है।
आइए यहां दो उदाहरण लेते हैं:
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);
}
}
अब आउटपुट पर एक नजर डालते हैं:
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]
अब आउटपुट का विश्लेषण करते हैं:
जब 3 संग्रह से हटा दिया जाता है तो यह संग्रह की remove()विधि को कॉल करता है जो Object oपैरामीटर के रूप में लेता है । इसलिए यह वस्तु को हटा देता है 3। लेकिन arrayList ऑब्जेक्ट में इसे इंडेक्स 3 द्वारा ओवरराइड किया जाता है और इसलिए 4 वें तत्व को हटा दिया जाता है।
ऑब्जेक्ट के एक ही तर्क द्वारा नल को दूसरे आउटपुट में दोनों मामलों में हटा दिया जाता है।
इसलिए 3जो संख्या एक वस्तु है उसे निकालने के लिए हमें स्पष्ट रूप से 3 को पास करने की आवश्यकता होगी object।
और रैपर क्लास का उपयोग करके कास्टिंग या रैपिंग द्वारा किया जा सकता है Integer।
उदाहरण के लिए:
Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);