问题描述
我有一个绑定对象和命令的泛型类:
初始化中 Iterator for(Iterator< OrderedObject< T>> it = s.iterator(); it.hasNext();){
我忽略了什么?
解决方案混乱是因为内部类 OrderedObjectSetIterator 引入了一个与外部类相同的泛型( T )。 Eclipse IDE显示一个警告:
类型参数T隐藏类型T
所以我猜你不需要引入另一个参数类型,只是使用与外部类相同的定义。
$ b基本上,内部类将被定义为:
private class OrderedObjectSetIterator实现Iterator< T> {
....
和迭代器方法一样:
public Iterator< T> iterator(){
return new OrderedObjectSetIterator();
}
I have a generic class which bundles an Object and an order:
public class OrderedObject<T> { private int order; private T object; public OrderedObject(int order, T object) { this.order = order; this.object = object; } public int getOrder() { return order; } public T getObject() { return object; } }I developed a Set implementation which stores OrderedObject<T> instances and wants to produce an Iterator<T> enumerating in the order enforced by the built-in order:
public class OrderedObjectSet<T> extends AbstractSet<T> implements Set<T> { Set<OrderedObject<T>> s = new HashSet<OrderedObject<T>>(); public boolean add(int order, T object) { return s.add(new OrderedObject<T>(order, object)); } public Iterator<T> iterator() { return new OrderedObjectSetIterator<T>(); } public int size() { return s.size(); } private class OrderedObjectSetIterator<T> implements Iterator<T> { private int index; public boolean hasNext() { return index < s.size(); } public T next() { T object = null; for (Iterator<OrderedObject<T>> it = s.iterator(); it.hasNext(); ) { OrderedObject<T> o = it.next(); if (o.getOrder() == index) { object = o.getObject(); } } index++; return object; } public void remove() { throw new UnsupportedOperationException(); } } }The latter class does not compile because there seems to some confusion of types in the Iterator initialization at
for (Iterator<OrderedObject<T>> it = s.iterator(); it.hasNext(); ) {What do I overlook?
解决方案The confusion is because the inner class OrderedObjectSetIterator introduces a generic type called the same (T) as the outer class. Eclipse IDE shows a warning:
The type parameter T is hiding the type TSo I guess you don't need to introduce another parameter type, just use the same as the outer class defines.
Basically, the inner class would be defined as:
private class OrderedObjectSetIterator implements Iterator<T> { ....And the iterator method as:
public Iterator<T> iterator() { return new OrderedObjectSetIterator(); }
这篇关于自定义Java迭代器类型混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!