Java 泛型方法和构造函数

2018-01-19 11:18 更新

例子

```class MyBag<T> {
private T ref;

public MyBag(T ref) {
this.ref = ref;
}

public T get() {
return ref;
}

public void set(T a) {
this.ref = a;
}
}
class Test<T>  {
public <V>  void  m1(MyBag<V>  a, MyBag<V>  b, T  c)  {

}
}
```

使用泛型方法

```class MyBag<T> {
private T ref;

public MyBag(T ref) {
this.ref = ref;
}

public T get() {
return ref;
}

public void set(T a) {
this.ref = a;
}
}
class Test<T> {
public <V> void m1(MyBag<V> a, MyBag<V> b, T c) {
}
}
public class Main {

public static void main(String[] argv) {
Test<String> t = new Test<String>();
MyBag<Integer> iw1 = new MyBag<Integer>(new Integer(201));
MyBag<Integer> iw2 = new MyBag<Integer>(new Integer(202));

// Specify that Integer is the actual type for the type parameter for m1()
t.<Integer>m1(iw1, iw2, "hello");

t.m1(iw1, iw2, "hello");
}
}
```

例2

```class MyBag<T> {
private T ref;

public MyBag(T ref) {
this.ref = ref;
}

public T get() {
return ref;
}

public void set(T a) {
this.ref = a;
}
}

public class Main {
public static <T> void copy(MyBag<T> source, MyBag<? super T> dest) {
T value = source.get();
dest.set(value);
}

public static void main(String[] argv) {
}
}
```

```Main.<Integer>copy(iw1, iw2);
```

泛型构造函数

```public class Test<T> {
public <U extends T> Test(U k) {
}
}
```

```class Test<T> {
public <U extends T> Test(U k) {
}
}

public class Main {
public static void main(String[] argv) {
// Specify the actual type parameter for the constructor as Double
Test<Number> t1 = new<Double> Test<Number>(new Double(1.9));

// Let the compiler figure out, Integer is
// the actual type parameter for the constructor
Test<Number> t2 = new Test<Number>(new Integer(1));

}
}
```

泛型对象创建中的类型推断

Java 7在泛型类型的对象创建表达式中增加了对类型推断的有限支持。

```List<String> list = new ArrayList<String>();
```

```List<String> list = new ArrayList<>();
```

```List<String> list = new ArrayList(); // Generates an  unchecked  warning
```

App下载