一、Iterator接口
所有实现Collection接口的容器类都有一个iterator()方法用来返回一个实现了Iterator接口的对象
Iterator对象称作迭代器,用来方便的实现对容器内元素的遍历操作。
package java.util; import java.util.function.Consumer; public interface Iterator<E> { * boolean hasNext(); //返回是否有元素为被遍历 E next(); //返回游标当前位置元素并将游标移动到下一个位置
default void remove() { throw new UnsupportedOperationException("remove"); } //删除游标左边的元素,因为在执行完next之后游标移到下一个元素,该操作只能执行一次 default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); }
二、List的遍历方式
/* * 测试List遍历的方式 * */ public class TestArrayList { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); //方式一,for循环遍历,通过get()方法 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } //方式二,while()循环,用迭代器实现 Iterator iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } //方式三,for循环,用迭代器实现 for (Iterator iterator1 = list.iterator(); iterator1.hasNext(); ) { System.out.println(iterator1.next()); } //方式四,增强for循环 foreach for (String str : list) { System.out.println(str); } //方式五,转化数组 String[] a = new String[3]; String[] aa = list.toArray(a); for (int i = 0; i < aa.length; i++) { System.out.println(aa[i]); } } }
ArrayList类中的定义内部类Itr,内部类实现Iterator接口
public Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; Itr() {} public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
三、Set遍历方式
HashSet中获取Iterator对象的方式
public Iterator<E> iterator() { return map.keySet().iterator(); }
public class TestHashSet { public static void main(String[] args) { Set<String> set = new HashSet(); set.add("aa"); set.add("bb"); set.add("cc"); //方式一,用while循环遍历,迭代器实现 Iterator iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } //方式二,用for循环遍历,迭代器实现 for (Iterator iterator1 = set.iterator(); iterator1.hasNext(); ) { System.out.println(iterator1.next()); } //方式三,增强for循环 for (String str : set) { System.out.println(str); } } }
四、Map的遍历方式
public class TestHashMap { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("a", "2000"); map.put("b", "3000"); //方式一、在for-each循环中使用entrySet来遍历 Set<Map.Entry<String, String>> entrySet = map.entrySet(); for (Map.Entry<String, String> entry : entrySet) { String key = entry.getKey(); String value = entry.getValue(); System.out.println("key=" +key+" value="+value); } //方式二、在for-each循环中通过键找值遍历 for (String key : map.keySet()) { System.out.println("key=" + key+" value="+map.get(key)); } //只打印键值keys for (String key : map.keySet()) { System.out.println("key=" + key); } //只打印values for (String value : map.values()) { System.out.println("value=" + value); } //方式三,使用iterator遍历 Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); System.out.println("key=" + entry.getKey() + " value=" + entry.getValue()); } //不使用泛型 Iterator iterator1 = map.entrySet().iterator(); while (iterator1.hasNext()) { Map.Entry entry1 = (Map.Entry) iterator1.next(); System.out.println("key=" + entry1.getKey() + " value=" + entry1.getValue()); } } }
public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es; }
public Set<K> keySet() { Set<K> ks = keySet; if (ks == null) { ks = new KeySet(); keySet = ks; } return ks; }