详见代码:
/**
* 类功能描述:
* Author:chenza
* Date:2011-12-23 上午12:17:53
*/
package basesdk.tech.generic;
import java.util.ArrayList;
import java.util.List;
import basesdk.tech.Human;
import basesdk.tech.Man;
public class WildCardGenericTest {
public void method(List<? extends Human> list) {
// do something...
}
public void test() {
// Man为Human的子类
List<? extends Human> list = new ArrayList<Human>();// OK
// List<? extends Human> list2 = new ArrayList<? extends Human>();//compile error
List<? extends Human> list3 = new ArrayList<Man>();// OK
this.method(list);// OK 说明参数传递只要符合继承关系即可
this.method(list3);// OK
//list.add(new Man());//compile error
//不能往其中加入任何类型的对象,因为list中的元素类型未知,
//这样做是为了保证类型安全
//=====================================
for (Human human : list) { // OK 根据List的定义,list中的元素为Human的子类(包括Human自身),
//根据变量赋值规则,父类可以引用任意子类,所以该段代码是正确的
}
for(Object obj : list){//OK 原因跟上面一样,Object类是所有类的父类
}
/*
for (Man Man : list) { // compile error
// 因为list中的类型为Human的子类,其中的元素可能Man,也可能不是,子类无法引用父类
//所以本段代码编译出错
}
*/
//=========================================
}
}
以下代码是完全正确的泛型应用
public List<? extends Target> getCollectTargetList(Object[] args) {
List<DemoTarget> demoList = new ArrayList<DemoTarget>();
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "select ap.ap_id,ap.ap_ip_addr from wlan_cm_ap ap where ap.ac_id = 0 and ap.area_id = " + args[0];
logger.info("SQL = " + sql);
try {
conn = this.openConnection();
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
DemoTarget target = new DemoTarget();
target.target_id = rs.getLong("ap_id");
target.name = rs.getString("ap_ip_addr");
demoList.add(target);
}
} catch (Exception e) {
logger.error("",e);
} finally{
this.closeStatement(pstmt);
this.closeConnection(conn);
}
return demoList;
}