Friday, November 12, 2010

Remove from wrapped set

Late breaking news. Ugh! Turns out that Set<String> ts = new TreeSet<String>(s) doesn't wrap (thanks rbohn). Not sure why I had it in my head that it did. It creates another Set that contains the elements from the first. That would explain it. It's kind of hard to get anywhere when your presuppositions are wrong!

===========================================================

If you wrap a set with something else TreeSet or ArrayList, etc. Then you iterate over the wrapped collection and call remove on the iterator your item will not be removed. How did I not know this? Have I forgotten? Did I never know?

public static void main(String[] args) {
    Set<String> s = new HashSet<String>();
    s.add("this");
    s.add("that");
    s.add("momma");
    Set<String> ts = new TreeSet<String>(s);
    for (Iterator<String> it = ts.iterator(); it.hasNext();) {
        String ss = it.next();
        if ("momma".equals(ss)) {
            it.remove();
        }
    }
    System.out.println(s);
}

The output of the above will be as shown below (in no specific order). Yo momma did not get removed.

[that, momma, this]

No comments:

Post a Comment