【问题标题】:Iterable for both generic and raw type可迭代泛型和原始类型
【发布时间】:2015-08-27 14:36:57
【问题描述】:

不使用泛型类型我有以下工作正常:

public class OC_GuillotinePacker implements Iterable<OC_GuillotinePacker> {
    @Override
    public Iterator<OC_GuillotinePacker> iterator() {
        // code that returns a new Iterator
    }
}

这让我可以像这样循环:

for (OC_GuillotinePacker gp : packer) {

}

我更新了我的代码,以便我可以通过它的泛型类型来存储对象。 现在是这样的:

public class OC_GuillotinePacker<T> implements Iterable<OC_GuillotinePacker<T>> {
    @Override
    public Iterator<OC_GuillotinePacker<T>> iterator() {
        // code that returns a new Iterator
    }
}

问题是当我创建一个新的 OC_GuillotinePacker 时:

packer = new OC_GuillotinePacker(0, 0, width, height); 

那我不能再这样循环了:

for (OC_GuillotinePacker gp : packer) {

}

它给了我一个不兼容的类型警告。需要的是 OC_GuillotinePacker,找到的是 java.lang.Object。

是否有可能使两者都成为可能?所以每个循环都有一个 raw 和一个泛型类型。

【问题讨论】:

  • 在实例化 OC_GuillotinePacker 时必须提供类型(例如,new OC_GuillotinePacker&lt;String&gt;)。在for循环中,你总是可以使用OC_GuillotinePacker&lt;?&gt;
  • 我并不总是想要一个类型。这是可选的。

标签: java generics iterable raw-types


【解决方案1】:

当您使用类型参数 TOC_GuillotinePacker 类设为泛型时,您的声明就变成了原始的。

packer = new OC_GuillotinePacker(0, 0, width, height);

当您使用原始类型时,会发生类型擦除,因此iterator() 方法现在返回原始Iterator,它返回Objects。 Object 不能分配给 OC_GuillotinePacker,因此出现错误。

创建OC_GuillotinePacker 时,提供类型参数或使用菱形运算符从packer 变量声明中推断类型。

packer = new OC_GuillotinePacker<>(0, 0, width, height);

这样,iterator() 方法将返回 OC_GuillotinePacker&lt;YourType&gt; 对象以在您的增强型 for 循环中使用。

for (OC_GuillotinePacker<YourType> gp : packer) {

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多