gpt4 book ai didi

java - Java 中使用原始类型方法的类型不匹配

转载 作者:行者123 更新时间:2023-11-30 03:54:12 25 4
gpt4 key购买 nike

这里有几个与在 Java 中使用泛型类型不匹配相关的问题,但我找不到与我的情况相对应的任何内容。

我想知道为什么下面的代码会发生这个错误?

Type mismatch: cannot convert from element type Object to String

排队

for (String element : arg.someMethod())

但是如果

SomeInterface arg

改为

SomeInterface<?> arg

它有效。为什么列表参数类型没有连接接口(interface)类型参数会被删除?

import java.util.List;

public class TypeMismatchExample
{
interface SomeInterface<P extends Object>
{
P someParametrizedMethod();

List<String> someMethod();
}

void example(SomeInterface arg)
{
for (String element : arg.someMethod())
{
// do something
}
}
}

最佳答案

当您的代码中有原始类型时,该类中的所有泛型类型信息都会丢失 - 因此,编译器不知道 someMethod返回 List类型 String .

JLS 的相关部分:Raw Types

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M 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.

既然您将方法参数声明为 SomeInterface ,这是一种原始类型,您无法利用泛型 someMethod ,即使其泛型类型参数与 P 不同。 .

关于java - Java 中使用原始类型方法的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667920/

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