迭代器Iterable和Iterator

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guyan1111/article/details/70312315

1:java.lang. Itreable 

            ---| Itreable      接口实现该接口可以使用增强for循环

              ---| Collection      描述所有集合共性的接口

                  ---| List接口     可以有重复元素的集合

                  ---| Set接口      不可以有重复元素的集合

Iterable只有一个方法Iterator(); 用于返回集合迭代器对象。

Iterator是Iterable的一个接口,一共有三种方法:

 boolean hasNext()
          如果仍有元素可以迭代,则返回 true
 E next()
          返回迭代的下一个元素。
 void remove()
          从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。

public static void main(String[] args) {
		Collection coll = new ArrayList();
		coll.add("234");
		coll.add("123");
		coll.add("345");
		coll.add("456");
		coll.add("789");
		// 输出集合
		System.out.println(coll);
		// 使用while遍历集合
		Iterator it = coll.iterator();
		System.out.println("使用while遍历的结果: ");
		while (it.hasNext()) {
			String str = (String) it.next();
			System.out.print(str + " ");
		}
		// 使用for循环遍历集合,java 建议使用for 循环。因为可以对内存进行一下优化。
		System.out.println('\n' + "使用for循环遍历的结果: ");
		for (Iterator it1 = coll.iterator(); it1.hasNext();) {
			String str = (String) it1.next();
			System.out.print(str + " ");

		}
		//使用迭代器清空集合
		Iterator it2 = coll.iterator();
		while(it2.hasNext()){
			//定位到要删除的元素的位置。
			it2.next();
			it2.remove();
			
			//coll.add("654");// 抛异常,出现了迭代器以外的对元素的操作
		}
		/**
		 * 细节一:如果迭代器的指针已经指向了集合的末尾,那么如果再调用next()会返回NoSuchElementException异常
		 * 细节二:如果调用remove之前没有调用next是不合法的,会抛出IllegalStateException异常
		 * 细节三:当一个集合在循环中即使用引用变量操作集合又使用迭代器操作集合对象, 会抛出ConcurrentModificationException异常
		 */
		System.out.println(coll);
	}

如果是List集合想要在遍历时操作元素,可以使用特有迭代器ListIterator,在迭代过程中可以添加和修改元素。具体详见下一篇博客。



猜你喜欢

转载自blog.csdn.net/guyan1111/article/details/70312315