【问题标题】:Java class with concrete type as parameter以具体类型为参数的 Java 类
【发布时间】:2013-11-29 22:19:49
【问题描述】:

将具有“具体”类型的类声明为泛型有什么意义?

如果是,它有什么用?

如果不是,编译器允许它的任何具体原因?

代码:

public class SomeClass<Integer> {  

    //...

    public static void main (String a[]) {
        // SomeClass <> iSome = new SomeClass<>();
        // SomeClass <Integer> jSome = new SomeClass<>();

        SomeClass <Double> kSome = new SomeClass<>();

        // ...
    }
}

运行良好,当我取消注释声明 iSomejSome 的行时出现编译器错误。

我正在尝试将所有东西放在一起“破译”泛型。

提前致谢。

【问题讨论】:

    标签: java generics


    【解决方案1】:

    这不是你想的那样。您正在创建一个名为 Integer 的泛型类型参数,它会影响 java.lang.Integer

    【讨论】:

    • 所以“Integer”没有被保留在那里——JVM没有检查它是否是java.lang中的一个类,公共类SomeClass相当于公共类SomeClass(?)
    • @Roam 是的,没错。名称 Integer 被您的泛型类型参数所掩盖。
    【解决方案2】:

    在类定义中,您称为Integer 的参数也可以只是T 而不会改变含义。

    AFIK 你可以在 Java 7 中省略泛型,编译器会自动添加它,它无论如何都不会在运行时存储。所以你必须在左手定义中定义泛型,唯一的例外是使用用作通配符的问号。

    // here is the generic missing the compiler cannot guess it:
    SomeClass<> iSome = new SomeClass<>();
    // here does the compiler know that you want a Double
    SomeClass<Double> jSome = new SomeClass<>();
    // this will also work
    SomeClass<?> kSome = new SomeClass<Boolean>();
    

    【讨论】:

      猜你喜欢
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多