[ajug-members] question from a new coder

Joe Drury joe.drury at gmail.com
Thu Dec 4 19:18:09 EST 2008


Kerry,

You can't modify the TreeSet while iterating through it.

*From:  http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeSet.html

**The Iterators returned by this class's iterator method are **fail-fast: if
the set is modified at any time after the iterator is created, in any way
except through the iterator's own remove method, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent
modification, the iterator fails quickly and cleanly, rather than risking
arbitrary, non-deterministic behavior at an undetermined time in the future.

*

You need to find another way to keep those Objects you want to keep from the
TreeSet.  I don't have a good editor on this pc nor have I attempted to
compile this code but something along these lines might work...

private TreeSet<String> cleanup(TreeSet<String> tSet){
        Iterator<String> iter = tSet.iterator();
        TreeSet<String> cleanTreeSet = new TreeSet<String>();
        while(iter.hasNext()){
            String s = (String)iter.next();
            if(s.endsWith("-8000")){
                tSet.remove(s);
                s = s.substring(0, s.length()-5);
                cleanTreeSet.add(s);
            } else if(s.endsWith("-443")){
                tSet.remove(s);
                s = s.substring(0, s.length()-5);
                cleanTreeSet.add(s);
            } else {
                cleanTreeSet.add(s);
            }
        }
        return cleanTreeSet;
    }

Hope this helps,

Joe Drury

2008/12/4 Kerry Randolph <kerry at randolph1.com>

> Hello all
>
> I'm fairly new to Java and not sure how to do this. Any help would be
> appreciated.
> I'm trying to iterate through a TreeSet and if any String element ends in
> "-8000" or "-443" I want to chop that part off.
> Here's what I'm trying, but getting a ConcurrentModificationException:
>
>     private TreeSet<String> cleanup(TreeSet<String> tSet){
>         Iterator<String> iter = tSet.iterator();
>         while(iter.hasNext()){
>             String s = (String)iter.next();
>             if(s.endsWith("-8000")){
>                 tSet.remove(s);
>                 s = s.substring(0, s.length()-5);
>                 tSet.add(s);
>             }
>             if(s.endsWith("-443")){
>                 tSet.remove(s);
>                 s = s.substring(0, s.length()-5);
>                 tSet.add(s);
>             }
>         }
>         return tSet;
>     }
>
> Thoughts????    Thanks for the help!!!
> --Kerry
>
> _______________________________________________
> ajug-members mailing list
> ajug-members at ajug.org
> http://www.ajug.org/mailman/listinfo/ajug-members
>
>


-- 
Joe Drury
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.ajug.org/pipermail/ajug-members/attachments/20081204/5322fe21/attachment.html 


More information about the ajug-members mailing list