Java基础学习笔记(十六)—— Iterator的使用与java常用容器的遍历方法

Java基础学习笔记(十六)—— Iterator的使用与java常用容器的遍历方法

Life was like a box of chocolates, you never know what you’re gonna get.

| @Author:TTODS

目录

      • Java基础学习笔记(十六)—— Iterator的使用与java常用容器的遍历方法
        • Iterator接口提供的方法
          • hasNext()
          • next()
          • remove()
          • forEachRemaining(Consumer action)
        • 常见容器的遍历
          • ArrayList与LinkedList
            • for语句
            • forEach语句
            • 迭代器
          • Set集合
            • forEach语句
            • 迭代器
          • Map


Iterator接口提供的方法

hasNext()

如果迭代具有更多元素,则返回 true 。

next()

返回迭代中的下一个元素。

ArrayList<Integer> myArray = new ArrayList<>();
myArray.add(5);
myArray.add(4);
myArray.add(3);
myArray.add(2);
myArray.add(1);
Iterator<Integer> iter = myArray.iterator();
while(iter.hasNext()) {
	System.out.println(iter.next());
}
/*
5
4
3
2
1
*/
remove()

从底层集合中删除此迭代器返回的最后一个元素(可选操作)。

ArrayList<Integer> myArray = new ArrayList<>();
myArray.add(5);
myArray.add(4);
myArray.add(3);
myArray.add(2);
myArray.add(1);
Iterator<Integer> iter = myArray.iterator();
System.out.println(myArray);
while(iter.hasNext()) {
	iter.next();
	iter.remove();
}
System.out.println(myArray);

输出:

[5, 4, 3, 2, 1]
[]
forEachRemaining(Consumer action)

对每个剩余元素执行给定的操作,直到所有元素都被处理或动作引发异常。

我们在java的官方文档中找不到Iterator的具体实现类,因为Iterator对象一般由容器类提供Iterator()方法返回来得到,可迭代的容器实现了接口Iterable,该接口要求子类实现Iterator()方法和forEach()方法。Iterator接口的实现一般在容器的内部进行。下面是ArrayList基于Iterator接口的实现类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();
   }
}

常见容器的遍历

ArrayList与LinkedList

ArrayList与LinkedList的遍历方法基本一样,下面以ArrayList为例

for语句
ArrayList<Integer> myArray = new ArrayList<>(Arrays.asList(5,4,3,2,1));
for(int index=0;index<myArray.size();index++)
	System.out.println(myArray.get(index));

输出

5
4
3
2
1
forEach语句
ArrayList<Integer> myArray = new ArrayList<>(Arrays.asList(5,4,3,2,1));
for(Integer num:myArray) {
	System.out.println(num);
}

输出

5
4
3
2
1
迭代器
ArrayList<Integer> myArray = new ArrayList<>(Arrays.asList(5,4,3,2,1));
Iterator<Integer> iter = myArray.iterator();
while(iter.hasNext())
	System.out.println(iter.next());

输出

5
4
3
2
1
Set集合

由于Set集合中的元素是无序的,所以我们不能使用for循环根据索引来遍历Set集合

forEach语句
HashSet<String>  myHashSet = new HashSet<>(Arrays.asList("one","two","three","four"));
for(String str:myHashSet) {
	System.out.println(str);
}

输出

four
one
two
three
迭代器
HashSet<String>  myHashSet = new HashSet<>(Arrays.asList("one","two","three","four"));
Iterator<String> iter = myHashSet.iterator();
while(iter.hasNext())
	System.out.println(iter.next());
}

输出

four
one
two
three
Map

Map是由一个Key集合,和一个Value容器组成的,遍历时可以单独的遍历Key集合,也可以单独的遍历Value容器,单独遍历的方法上面已经展示过了,下面代码仅演示如何通过Key集合来遍历Value容器

HashMap<Integer,Character> myHashMap = new HashMap<>();
myHashMap.put(1,'A');
myHashMap.put(2,'B');
myHashMap.put(3,'C');
myHashMap.put(4,'D');
myHashMap.put(5,null);
Set<Integer> keys = myHashMap.keySet();
for(Integer key:keys) {
	System.out.println(key+"=>"+myHashMap.get(key));
}

输出

1=>A
2=>B
3=>C
4=>D
5=>null

- THE END -

你可能感兴趣的:(java基础学习笔记)