收藏 分销(赏)

自定义Java迭代器.docx

上传人:s4****5z 文档编号:8088260 上传时间:2025-02-04 格式:DOCX 页数:5 大小:21.15KB 下载积分:10 金币
下载 相关 举报
自定义Java迭代器.docx_第1页
第1页 / 共5页
自定义Java迭代器.docx_第2页
第2页 / 共5页


点击查看更多>>
资源描述
Java Iterator To generate successive elements from a series, we can use java iterator. It is an improvement over Enumeration interface. Iterator takes the place of Enumeration since jdk 1.2 It is a nice utility for collections. Every collection is unique on its own and imagine if we have have to write logic on our own for every collection when there is a need to iterate it. Instead, java forces a collection to deliver an iterator. These nice utilities makes java lovable, isn’t it? Important points to note: · We can iterate only in one direction · Iteration can be done only once. If you reach the end of series its done. If we need to iterate again we should get a new Iterator. Iterator Example without Generics package com.javapapers; import java.util.ArrayList; import java.util.Iterator; public class ExampleIterator { public static void main(String args[]){ ArrayList animal = new ArrayList(); animal.add("Horse"); animal.add("Lion"); animal.add("Tiger"); Iterator animalItr = animal.iterator(); while(animalItr.hasNext()) { String animalObj = (String)animalItr.next(); System.out.println(animalObj); } } } Without generics, Iterator returns the Object and we need to typecast it. Ads by Google Iterator Example using Generics package com.javapapers; import java.util.ArrayList; public class ExampleIterator { public static void main(String args[]){ ArrayList<String> animal = new ArrayList<String>(); animal.add("Horse"); animal.add("Lion"); animal.add("Tiger"); for(String animalObj : animal) { System.out.println(animalObj); } } } Output: Horse Lion Tiger Look how simple it is. There is no reference to the Iterator explicitly since we are using for-each of generics. Iterable and Iterator To make an object iterable it needs to emit an Iterator object. To enforce this contract, Iterator interface is to be used. It contains a method named iterator() and it returns Iterator. Hence, any class that implements Iterable will return an Iterator. public interface Collection<E> extends Iterable<E> { For example take any Collection. A Collection is an interface that represents container for series of elements. Every collections like ArrayList, Vector implements Collection and so Iterator. · One advantage of Iterable is, when you implement Iterable then those object gets support for for:each loop syntax. Removing elements using Iterator · Iterator has a remove method using which we can delete elements from the underlying object. · It removes the last element returned by the iterator. Difference between Iterator and Enumeration interfaces 1. remove() method is introduced in iterator. Using this method we can remove element from the underlying collection which we are iterating. 2. Enumeration has two methods and both are available in iterator. Method names for both of them are shortened. ListIterator an even better Iterator for a List containing more utility methods like getting index of elements and adding elements to the base object. Using ListIterator we can iterate in both the directions. ConcurrentModificationException Look at the following code, it throws ConcurrentModificationException. We cannot add or remove elements to the underlying collection when we are using an iterator. Implementing our own Custom Iterator We will create our own custom class and make it implement Iterable, so that it returns an Iterator using which we can iterate the elements. package com.javapapers; import java.util.ArrayList; public class ExampleIterator { public static void main(String args[]){ ArrayList<String> animal = new ArrayList<String>(); animal.add("Horse"); animal.add("Lion"); animal.add("Tiger"); for(String animalObj : animal) { System.out.println(animalObj); animal.add("Hyena"); } } } Output: Horse Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) at com.javapapers.ExampleIterator.main(ExampleIterator.java:13) package com.javapapers; import java.util.ArrayList; import java.util.Iterator; public class AnimalIterator<String> implements Iterator<Object> { private ArrayList<?> animal; private int position; public AnimalIterator(Animal animalBase) { this.animal = animalBase.getAnimal(); } @Override public boolean hasNext() { if (position < animal.size()) return true; else return false; } @Override public Object next() { Object aniObj = animal.get(position); position++; return aniObj; } @Override public void remove() { animal.remove(position); } } package com.javapapers; import java.util.ArrayList; import java.util.Iterator; public class Animal implements Iterable<String> { private ArrayList<String> animal = new ArrayList<String>(); public Animal(ArrayList animal){ this.animal = animal; } public ArrayList getAnimal() { return animal; } @Override public Iterator<String> iterator() { return new AnimalIterator(this); } } package com.javapapers; import java.util.ArrayList; public class TestIterator { public static void main(String args[]) { ArrayList<String> animalList = new ArrayList(); animalList.add("Horse"); animalList.add("Lion"); animalList.add("Tiger"); Animal animal = new Animal(animalList); for (String animalObj : animal) { System.out.println(animalObj); } } } Output: Horse Lion Tiger
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传

当前位置:首页 > 百科休闲 > 其他

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服