Last active
December 26, 2015 20:09
-
-
Save pk13610/7207035 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package BaseType; | |
import java.util.Iterator; | |
public class IterableLinkList<T> extends SimpleLinkList<T> implements Iterable<T> { | |
// Iterable support | |
public Iterator<T> iterator(){ | |
// 所谓的返回匿名类 | |
return new Iterator<T>(){ | |
private int cur = 0; | |
@Override | |
public boolean hasNext() { | |
return this.cur < IterableLinkList.this.size(); | |
} | |
@Override | |
public T next() { | |
try { | |
return IterableLinkList.this.indexOf(this.cur++); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
@Override | |
public void remove() { | |
try { | |
IterableLinkList.this.remove(this.cur-1); | |
this.cur--; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
}; | |
} | |
// for test | |
private static void print_list(SimpleLinkList mylist, String msg) throws Exception{ | |
System.out.println("======= " + msg + " =====" + mylist.size()); | |
for(int i=0; i<mylist.size(); ++i){ | |
System.out.println(mylist.indexOf(i)); | |
} | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
// test for iterator support | |
IterableLinkList<String> mylist = new IterableLinkList<String>(); | |
for(int i=0; i<10; ++i){ | |
mylist.add(new String(Integer.toString(i))); | |
} | |
System.out.println("======================== traversal"); | |
for(String data : mylist){ | |
System.out.println(data); | |
} | |
System.out.println("======================== remove"); | |
for(Iterator itr = mylist.iterator(); itr.hasNext();){ | |
itr.next(); | |
itr.remove(); | |
} | |
for(String data : mylist){ | |
System.out.println(data); | |
} | |
assert(mylist.size() > 0); | |
System.out.println("remove test ok!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment