java容器之Iterator(迭代器)
Method Summary
boolean |
hasNext()
Returns
true if the iteration has more elements.
判断游标右边是否有元素
|
E |
next()
Returns the next element in the iteration.
返回游标右边的元素,并将游标移动到下一位置
|
default void |
remove()
Removes from the underlying collection the last element returned by this iterator (optional operation).
删除游标左边的元素
|
TestIterator.java
import java.util.*; //Iterator迭代器测试 public class TestIterator { public static void main(String[] args) { Collection c = new HashSet(); c.add(new Name("f1","l1")); c.add(new Name("f2","l2")); c.add(new Name("f3","l3")); Iterator i = c.iterator(); //判断游标右边是否有元素 while(i.hasNext()){ //next()的返回值要强制转换为对应的对象类型 Name n = (Name)i.next(); System.out.println(n.getFirstName() + " "); } System.out.println(); /////////////////////////////////// Collection c2 = new HashSet(); c2.add(new Name("f1111","l1111")); c2.add(new Name("f2","l2")); c2.add(new Name("f3333","l3333")); for(Iterator it = c2.iterator(); it.hasNext();){ Name name = (Name)it.next(); if(name.getFirstName().length() < 3){ it.remove(); //如果换成c.remove(name)会产生例外 } } System.out.println(c2);//[f1111 l1111, f3333 l3333] } } class Name /*implements Comparable*/ { private String firstName,lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String toString() { return firstName + " " + lastName; } /** * 重写equals方法 */ public boolean equals(Object obj) { if (obj instanceof Name) { Name name = (Name) obj; return (firstName.equals(name.firstName)) && (lastName.equals(name.lastName)); } return super.equals(obj); } /** * 重写hashCode方法 */ public int hashCode() { return firstName.hashCode(); } }
F:\java>javac TestIterator.java 注: TestIterator.java使用了未经检查或不安全的操作。 注: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。 F:\java>java TestIterator f1 f2 f3 [f1111 l1111, f3333 l3333] F:\java>