0

Colletions从课堂上研究这种方法:

@SuppressWarnings("unchecked")
    public static final <T> Set<T> emptySet() {
        return (Set<T>) EMPTY_SET;
    }

Collections.emptySet() return `Set<Object>`

这种行为不同于泛型类。<T>如果我在没有使用原始对象的情况下实例化泛型类。

在方法接受泛型集因编译错误而失败后,我注意到了这一点:

public class GenericMethodRaw {
    public static void main(String [] args){
        Set set = Collections.emptySet();
        method(set); //fine
        method(Collections.emptySet());  //compilation error here
        Set<String> set1 = Collections.emptySet();//fine compilation
    }
    public static void method(Set<String> strings){}
}

编译器消息:

java: method method in class GenericMethodRaw cannot be applied to given types;
  required: java.util.Set<java.lang.String>
  found: java.util.Set<java.lang.Object>
  reason: actual argument java.util.Set<java.lang.Object> cannot be converted to java.util.Set<java.lang.String> by method invocation conversion
4

3 回答 3

1

术语明智的,一个对象不是raw. 参考值的类型可以是。方法返回值的类型必须与方法的返回类型兼容。在emptySet方法上是因为演员。

在任何情况下,客户端永远不会看到调用中发生了什么,他们只知道方法调用表达式具有基于其调用上下文的类型。

于 2014-08-08T14:52:39.477 回答
0

是的,在具体示例中是可能的:

Collections类为此具有公共字段:

Collections.EMPTY_SET

一般来说,您不能使用通用方法的原始版本。编译器无论如何都会尝试评估类型。

于 2014-08-09T08:19:30.473 回答
0

如果您确实需要使用原始对象创建集合,请考虑使用通配符创建它。

Set<?> set = Collections.emptySet();
于 2014-08-08T15:02:30.433 回答