栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中将迭代器实现为类的属性

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中将迭代器实现为类的属性

将迭代器维护为类的实例变量是非常不寻常的。您只能遍历一次数组-
可能不是您想要的。您更可能希望您的类为要遍历数组的任何人提供一个迭代器。下面是一个更传统的迭代器。

Java 5+代码-我没有尝试编译或运行,因此可能包含错误(当前不在开发机器附近)。它还使用自动装箱转换

Integer
int

public class MyArray implements Iterable<Integer> {    public static class MyIterator implements Iterator<Integer> {        private final MyArray myArray;        private int current;        MyIterator(MyArray myArray) { this.myArray = myArray; this.current = myArray.start;        }        @Override        public boolean hasNext() { return current < myArray.end;        }        @Override        public Integer next() { if (! hasNext())   throw new NoSuchElementException(); return myArray.arr[current++];        }        @Override        public void remove() { // Choose exception or implementation:  throw new OperationNotSupportedException(); // or //// if (! hasNext())   throw new NoSuchElementException(); //// if (currrent + 1 < myArray.end) { ////     System.arraycopy(myArray.arr, current+1, myArray.arr, current, myArray.end - current-1); //// } //// myArray.end--;        }    }    ....    // Most of the rest of MyArray is the same except adding a new iterator method ....    public Iterator<Integer> iterator() {        return new MyIterator();    }    // The rest of MyArray is the same ....}

另请注意:请注意不要超过静态数组的500个元素限制。如果可以,请考虑使用ArrayList类。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570034.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号