JDK高级特性--有限通配符泛型

本文详细阐述了Java泛型的使用方式及其类型安全机制,通过实例代码展示如何正确地利用泛型进行类型约束,避免运行时错误,并讨论了如何在集合中添加和遍历元素时确保类型一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详见代码:

/**
 * 类功能描述:
 * 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;
	}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值