本文介绍了如果实例没有分配通用类型,则泛型将用于每个循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么明确需要为ForEachLoop实例指定泛型类型?



为什么编译器会抱怨: 类型不匹配:无法从元素类型Object转换为字符串



JDK 1.5.0_09

  import java.util.ArrayList; 
import java.util.Collection;

public class ForEachLoop< T> {

public static void main(String [] args){

//非功能版本
ForEachLoop f = new ForEachLoop();

//功能版本
// ForEachLoop<整数> f = new ForEachLoop();

//类型不匹配:无法从元素类型Object转换为字符串
for(String a:f.getStrings()){
System.out.println(a);
}
}

public Collection< String> getStrings(){
Collection< String> strings = new ArrayList< String>();
strings.add(Hello);
返回字符串;
}

}


解决方案

这是一个相当常见的错误:

  ForEachLoop f = new ForEachLoop(); 

应该是

  foreach循环<东西> f = new ForEachLoop< Something>(); 

如果您使用原始类型(您不应该这样做),编译器将删除所有通用信息即使它不是类型参数T,也可以使它与pre 1.5代码兼容。



如果您要编写Java 1.4或更低版本,请仅使用原始类型,在这种情况下,你不应该有任何泛型。在字节码级别,该方法在类型擦除后返回一个Collection(raw)。通常,如果实例具有泛型类型集,那么当您尝试对集合执行 get 时,编译器将使用通用信息来决定它应该返回一个String,然后在字节码级别,它会自动将它从Collection收到的Object转换为String(因为它保证是一个String)。但是,如果使用原始类型,编译器将忽略所有通用信息,并且不会自动为您再次投射对象。



编辑:In在原始类型的部分有这些东西:

请注意,Inner类具有独立于Outer类的类型参数,并且它仍然被擦除。基本上他们不希望我们在同一个实例中混合原始类型和泛型类型,因为它在任何版本中都没有意义(在1.5之前,通用部分将是错误,在1.5+以上,原始类型不鼓励,以及甚至可能会从未来的版本中删除)



然后也是这样:
$ b

Notice that the Inner class has it's own type parameter independent of the one of the Outer class, and it still gets erased. Basically they don't want us mixing raw and generic types on the same instance, since it doesn't make sense in any version (in pre 1.5, the generic part will be an error, in 1.5+ the raw type is discouraged, and may even be removed from future versions)

Then there's also this:

which says that constructors, instance methods and non-static fields will be treated as raw in a raw instance. Static members will be treated as generic anyway, since they don't require an instance to be accesed.

这篇关于如果实例没有分配通用类型,则泛型将用于每个循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:15