This blog demonstrates difference between ArrayList remove() method
and Collection remove() method that we use and face below types of problem:–
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[code] import java.util.*; public class UsingCollection{ public static void main(String[] args) { ArrayList<String> lst = new ArrayList<String>(); Collection<String> col = lst; lst.add("one" ); lst.add("two" ); lst.add("three" ); lst.remove(0); col.remove(0); System.out.println("Added three items, remove two, so 1 item to remain." ); System.out.println("Number of elements is: " + lst.size()); System.out.println("Number of elements is: " + col.size()); } }[/code] |
The output from the previous code is as follows:
Added three items, remove two, so 1 item to remain.
Number of elements is: 2
Number of elements is: 2
Question : don’t make any change’s in elements why???
MyAnswer :
Reason :
Collection remove
-
- :
- boolean remove(Object o)
Removes a single instance of the specified element from this collection, if it is present (optional operation).
ArrayList remove
-
- :
- boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present. - E remove(int index)
Removes the element at the specified position in this list.
-
- Now in above case
- lst.remove(0) is removing element by using remove(int index)
- col.remove(0) is not removing any element because Object ‘0’ is not available in list.
try this!!!!!!!!!
Number of elements is: 2
nice concept sir!!!
thanks sir