A rare one that is explained more clearly:(

Generic wildcard<? Extends T>is used to receive the returned data. Generic collections with this notation cannot use the add method, while<? Super T>cannot use the get method, as it is prone to errors when assigning values as an interface call.

Explanation: To elaborate on the PECS (Producer Extend Consumer Super) principle:

  1. For those who frequently read content outside, it is suitable to use upper bound extends.
  2. Often inserted, suitable for using the lower bound Super.

A few specific examples (note: java.util.java is the parent class of java.sql.Timestamp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 上界用extends关键字声明,表示参数化的类型可能是所指定的类型,或者是此类型的子类
public void upperBound(List<? extends Date> list, Date date) {
Date now = list.get(0);
System.out.println("now==>" + now);
//list.add(date); //这句话无法编译
list.add(null);//这句可以编译,因为null没有类型信息
}

public void testUpperBound() {
List<Timestamp> list = new ArrayList<Timestamp>();
Date date = new Date();
upperBound(list,date);
}

# 泛型方法解决方法上面add问题
public <T extends Date> void upperBound2(List<T> list, T date) {
list.add(date);
}

public void testUpperBound2() {
List<Timestamp> list = new ArrayList<Timestamp>();
Date date = new Date();
Timestamp time = new Timestamp(date.getTime());
upperBound2(list,time);
//upperBound2(list,date);//这句同样无法编译
}

# 下界用super进行声明,表示参数化的类型可能是所指定的类型,或者是此类型的父类型,直至Object
public void lowerBound(List<? super Timestamp> list) {
Timestamp now = new Timestamp(System.currentTimeMillis());
list.add(now);
//下面语句不能编译,类型察除后变为:Timestamp time = (Timestamp)list.get(0);
//Timestamp time = list.get(0);
}

public void testLowerBound() {
List<Date> list = new ArrayList<Date>();
list.add(new Date());
lowerBound(list);
}

###Reference
阿里java规范

< http://fyting.iteye.com/blog/122732 >