Brainteaser: ArrayList VS TreeSet
When I came across the following example I did not expect the results that the program has printed :) hehe...
Question: What does this program print? Why?
Resources:
Effective Java
If you like this post, then consider subscribing to the full feed RSS.
Question: What does this program print? Why?
import java.util.*;Looking forward for your answers dear readers
public class SetList {
public static void main(String[] args) {
Set<Integer> set =
new TreeSet<Integer>();
List<Integer> list =
new ArrayList<Integer>();
for (int i = -3; i < 3; i++) {
set.add(i);
list.add(i);
}
for (int i = 0; i < 3; i++) {
set.remove(i);
list.remove(i);
}
System.out.println(set + " " + list);
}
}
Resources:
Effective Java
Related Posts
Brainteaser Drools: Testing Objects
Brainteaser: Broken case of inheritance
Brainteaser: Overridable methods
How to set SecurityManager and Java security policy programmatically
Hack any Java class using reflection attack
Brainteaser: Broken comparator
Singleton pattern and problem with double checked locking
Brainteaser: Hidden iterators
If you like this post, then consider subscribing to the full feed RSS.
Re: Brainteaser: ArrayList VS TreeSet
Just a guess..
Since list maintain the order of insertion in the collection, remove method in the list class might take the index of the object to be removed.. so list.remove(0) will remove zeroth element..
Where as Tree Set stores elements in sorted order, remove(index) does not make sense.. so remove(0) might remove element whose value is 0 instead of zeroth element..
I did not try.. just guessing.. ofcourse I will try now..
Since list maintain the order of insertion in the collection, remove method in the list class might take the index of the object to be removed.. so list.remove(0) will remove zeroth element..
Where as Tree Set stores elements in sorted order, remove(index) does not make sense.. so remove(0) might remove element whose value is 0 instead of zeroth element..
I did not try.. just guessing.. ofcourse I will try now..
Re: Brainteaser: ArrayList VS TreeSet
I agree with both of the above comments that List.remove(index) is the method that gets called on the List type, BUT the specification of this method additionally states that as a consequence all elements with a greater index are shifted to the left. Taking this into account: the list should print -2,0,2.
















