java - Implementing an Iterator for a Set, tracking the current element -


how code iterator set? given iterator not have access underlying data storage mechanism, , can use set methods, possible this?

every implementation i've managed find creates iterator anonymous class; however, trying figure out if there clever way iterate on set while accessing methods provided set.

so far, best i've managed come looks this:

import java.util.*;  public class setiterator<e> implements iterator {     protected e[] arraydata;     protected set<e> set;     protected int index;     protected boolean canremove;      public setiterator(set<e> set)     {         this.set = set;         this.arraydata = (e[]) set.toarray();         this.index = -1;         this.canremove = false;     }      public e next()     {         if(this.hasnext())         {             this.canremove = true;             return this.arraydata[++this.index];         }         else         {             throw new nosuchelementexception("there no next element");         }     }      public boolean hasnext()     {         return this.index + 1 < this.arraydata.length;     }      public void remove()     {         if(this.canremove)         {             this.set.remove(this.arraydata[index--]);             this.arraydata = (e[]) this.set.toarray();             this.canremove = false;         }         else         {             throw new illegalstateexception("cannot remove element before calling next");         }     } } 

but feels quite kludgy.... there better way?

i think title doesn't leave space answers, if use following actual question:

how build iterator set?

(and understand build in get instance of)

i think pm 77-1 pointed out in comments: call iterator() method on it, has since at least java 1.5.

keep in mind depends on actual implementation of set, wether elements iterated on in same order.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -