[英]Incompatible Types, but it doesn't make sense(Java)
I'm trying to iterate through a set and I want to save the next element in a temporary variable, but it is giving me a compilation error for incompatible types. 我正在尝试遍历一个集合,并且想将下一个元素保存在一个临时变量中,但这给了我不兼容类型的编译错误。
Iterator it = this.iterator();
E next = it.next();
next() returns a generic type E and next is of type E. Why is it giving me the error? next()返回通用类型E,下一个返回E类型。为什么会给我错误?
You're using Iterator
as a raw type, since you haven't provided a type argument. 由于未提供类型参数,因此您将
Iterator
用作原始类型。 When you use raw types, any related generic types become their erasure . 当您使用原始类型时,所有相关的通用类型都将被删除 。 In other words, any use of a class type variable in methods parameter, return types, etc. become either
Object
or the upper bound. 换句话说,在方法参数,返回类型等中对类类型变量的任何使用都将成为
Object
或上限。
You probably want 你可能想要
Iterator<E> it = this.iterator();
E next = it.next();
if this.iterator()
has a return type of Iterator<E>
. 如果
this.iterator()
的返回类型为Iterator<E>
。
You are using raw type iterator, use it with Generics, then it will allow to compile 您正在使用原始类型迭代器,将其与泛型一起使用,那么它将允许编译
Iterator<E> it = this.iterator();
E next = it.next();
使用泛型或类型转换到对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.