java容器之Iterator(迭代器)

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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值