Java 7的菱形语法与泛型构造器

一 实战——泛型构造器

1 代码

class Foo
{
   public <T> Foo(T t)
   {
      System.out.println(t);
   }
}
public class GenericConstructor
{
   public static void main(String[] args)
   {
      // 泛型构造器中的T参数为String。
      new Foo("疯狂Java讲义");
      // 泛型构造器中的T参数为Integer。
      new Foo(200);
      // 显式指定泛型构造器中的T参数为String,
      // 传给Foo构造器的实参也是String对象,完全正确。
      new <String> Foo("疯狂Android讲义");
      // 显式指定泛型构造器中的T参数为String,
      // 但传给Foo构造器的实参是Double对象,下面代码出错
      //new <String> Foo(12.3);
   }
}

2 运行

疯狂Java讲义
200
疯狂Android讲义

二 实战——泛型构造器和菱形语法混用

1 代码

class MyClass<E>
{
   public <T> MyClass(T t)
   {
      System.out.println("t参数的值为:" + t);
   }
}
public class GenericDiamondTest
{
   public static void main(String[] args)
   {
      // MyClass类声明中的E形参是String类型。
      // 泛型构造器中声明的T形参是Integer类型
      MyClass<String> mc1 = new MyClass<>(5);
      // 显式指定泛型构造器中声明的T形参是Integer类型,
      MyClass<String> mc2 = new <Integer> MyClass<String>(5);
      // MyClass类声明中的E形参是String类型。
      // 如果显式指定泛型构造器中声明的T形参是Integer类型
      // 此时就不能使用"菱形"语法,下面代码是错的。
//    MyClass<String> mc3 = new <Integer> MyClass<>(5);
   }
}

2 运行

t参数的值为:5
t参数的值为:5

3 说明

如果程序显示指定了泛型构造器中声明的形参的实际类型,则不可以使用菱形语法。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/94767871