Java容器之Iterator接口

Iterator 接口:

  1. 所有实现了Collection接口的容器类都有一个iterator方法用以返回一个实现了Iterator接口的对象.

  2. Iterator 对象称作迭代器,用以方便的实现对容器内元素的遍历操作.

  3. Iterator 接口定义了如下方法:

    boolean hasNext():如果仍有元素可以迭代,则返回 true;

      object next():返回迭代的下一个元素。抛出:NoSuchElementException - 没有元素可以迭代;

    void remove():删除游标左边的元素,在执行完next之后,该操作只能执行一次.

 

【注】:Iterator 就是一个统一的用来遍历Collection中所有元素的方法;

Demo_1:

import java.util.*;
class Name {
	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;
	}
}
public class Test {
	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();  // 使用迭代器访问HashSet中的每一个元素(要求每个元素类型一致)
		while(i.hasNext()){             
			Name n = (Name)i.next(); // next()返回值为object类型,需要转换为相应类型
			System.out.println(n);
		}
	}
}

 Demo_1 运行结果:

f3  l3
f1  l1
f2  l2

Demo_2:

import java.util.*;
class Name {
	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;
	}
}
public class Test {
	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"));
		c.add(12.59);
		c.add("Hello");
		ArrayList cc = new ArrayList(c); // 不适用迭代器访问Set中的元素
		for(int i=0;i<cc.size();i++){
			System.out.println(cc.get(i));
		}
	}
}

  Demo_2 运行结果:

f3  l3
12.59
Hello
f1  l1
f2  l2

  Demo_3:

import java.util.*;
public class Test {
	public static void main(String[] args) {
		Collection c = new HashSet(); // 
		c.add(123);
		c.add(123.56);
		c.add(234);
		c.add(32);
		c.add("hello");
		Iterator i = c.iterator();
		while(i.hasNext()){
			System.out.println(i.next());
		}
	}
}

 Demo_3 运行结果:

123.56
32
234
123
hello

Iterator 对象的 remove 方法是在迭代过程中删除元素的唯一安全的方法:

import java.util.*;
public class Test {
	public static void main(String[] args) {
		HashSet c = new HashSet();
		c.add("hello");
		c.add("you");
		c.add("are");
		c.add("good");
		c.add("Hoodlum");
		for(Iterator i = c.iterator();i.hasNext();){
			if(i.next().toString().length()<4){
				i.remove();
			}
		}
		System.out.println(c);
	}
}

 运行结果:[hello, good, Hoodlum]

原文地址:https://www.cnblogs.com/bosongokay/p/6767190.html