gpt4 book ai didi

java - 什么是有界泛型的删除?

转载 作者:行者123 更新时间:2023-11-30 06:49:43 25 4
gpt4 key购买 nike

我有一个泛型类。我知道泛型类型信息在运行时被剥离,但这是绑定(bind)类型。我认为在编译时 java.lang.Object 被绑定(bind)类型替换。如果我知道一切都至少是一个 Animal,那么为什么编译器将它保留为 Object?有什么我想念的东西可以使这项工作像我想要的那样吗?具体来说,main 方法中的最后一个 for 循环存在编译时问题。

谢谢!

public static void main( String[] args ) throws Exception {

Litter<Cat> catLitter = new Litter<>();
for( Cat cat : catLitter ) {}

Litter<Animal> animalLitter = new Litter<>();
for( Animal animal : animalLitter ) {}

Litter litter = new Litter();
for( Animal animal : litter ) {} // Type mismatch: cannot convert from element type Object to Animal
}

public class Litter<T extends Animal> implements Iterable<T>{
@Override public java.util.Iterator<T> iterator() {
return new LitterIterator();
}

class LitterIterator implements java.util.Iterator<T> {
@Override public boolean hasNext() { return false; }
@Override public T next() { return null; }
}
}

public class Animal {}
public class Dog extends Animal{}
public class Cat extends Animal{}

最佳答案

强制重定向:

您期望的行为将适用于类似的东西

public class Litter<T extends Animal> implements Iterable<T>{
public T get() {return null; /* or whatever */}
...
}

Litter litter = ...; // raw type 
Animal animal = litter.get(); // compiles fine

Litterraw type

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C

自从

The erasure of a type variable (§4.4) is the erasure of its leftmost bound.

然后是方法get显示为

public Animal get() {...}

使用原始代码 Litter类型。

至于Litter#iterator()但是,它的返回类型是 Iterator<T>自从

The erasure of a parameterized type (§4.5) G<T1,...,Tn> is |G|.

它的删除只是Iterator . next() Iterator的方法|然后被删除到

public Object next() {...}

所以很明显它的返回值不能赋值给Animal类型的变量.

Is there something I'm missing that would make this work like I want?

不适用于原始类型,不。

关于java - 什么是有界泛型的删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42398260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com