Iterator:迭代器(接口),提供了统一的语法进行集合对象遍历操作.
主要方法:
hasNext() --判断是否还有下一个对象,如果有,则返回true,否则false;
next() --返回集合的下个值,此方法只能在hasNext方法返回true时调用;
remove() --删除集合的当前值,此方法也只能在hasNext方法返回true时调用
Iterable:该接口是为了foreach循环设计的,只有一个方法表示可以返回Iterator对象,最终还是使用Iterator遍历;所有Collection集合都实现了该接口,可直接foreach遍历。
例子
public static void main(String[] args) { List<Integer> li = new ArrayList<>(); LinkedList<String> strings = new LinkedList<>(); li.add(1); li.add(2); li.add(3); /*for (Integer integer : li) { System.out.println(integer); }*/ Iterator<Integer> iter = li.iterator(); while (iter.hasNext()){ System.out.print(iter.next()); iter.remove();//会删除原集合元素 } } 复制代码
让自己的类支持迭代
No1:
public class Main { public static void main(String[] args) { MyString ss=new MyString("123"); for (Character c:ss){ System.out.print(c); } } } 复制代码
class MyString implements Iterable<Character>{ private int length=0; private String str=""; public MyString(String str){ this.str=str; this.length=str.length(); } @Override public Iterator<Character> iterator() { return new Iter(); } class Iter implements Iterator<Character>{ private int curr=0; @Override public boolean hasNext() { return curr!=length; } @Override public Character next() { Character c=str.charAt(curr); curr++;//后移 return c; } } } 复制代码
public class Test { public static void main(String[] args)throws Exception { Stack<String> stack = new Stack<>(); stack.push("a"); stack.push("b"); stack.push("c"); stack.push("d"); for (String str : stack) { System.out.print(str+" "); } System.out.println("-----------------------------"); String result = stack.pop(); System.out.println("弹出了元素:"+result); System.out.println(stack.size()); } } 复制代码
public class Stack<T> implements Iterable<T>{ //记录首结点 private Node head; //栈中元素的个数 private int N; public Stack() { head = new Node(null,null); N=0; } //判断当前栈中元素个数是否为0 public boolean isEmpty(){ return N==0; } //把t元素压入栈 public void push(T t){ Node oldNext = head.next; Node node = new Node(t, oldNext); head.next = node; //个数+1 N++; } //弹出栈顶元素 public T pop(){ Node oldNext = head.next; if (oldNext==null){ return null; } //删除首个元素 head.next = head.next.next; //个数-1 N--; return oldNext.item; } //获取栈中元素的个数 public int size(){ return N; } @Override public Iterator<T> iterator() { return new SIterator(); } private class SIterator implements Iterator<T>{ private Node n = head; @Override public boolean hasNext() { return n.next!=null; } @Override public T next() { Node node = n.next; n = n.next; return node.item; } } private class Node{ public T item; public Node next; public Node(T item, Node next) { this.item = item; this.next = next; } } } 复制代码