【ThinkingInJava】28、泛型类的语法

/**
* 书本:《Thinking In Java》
* 功能:泛型类的语法
* 文件:FilledList.java
* 时间:2015年4月13日16:33:58
* 作者:cutter_point
*/
package Lesson14TypeInformation;

import java.util.ArrayList;
import java.util.List;

class CountedInteger
{
	private static long counter;
	private final long id = counter++;
	public String toString()
	{
		return Long.toString(id);
	}
}

public class FilledList<T> 
{
	private Class<T> type;	//前面那个CLass<T>是T类型的一个引用
	
	public FilledList(Class<T> type) { this.type = type; }	//构造函数
	
	public List<T> create(int nElements)		//创建一个int序列
	{
		//用一个ArrayList存放序列
		List<T> result = new ArrayList<T>();
		
		//循环添加到序列中
		try 
		{
			for(int i = 0; i < nElements; ++i)
			{
				result.add(type.newInstance());	//添加一个type生成的类型
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		return result;
	}

	public static void main(String[] args) 
	{
		FilledList<CountedInteger> f1 = new FilledList<CountedInteger>(CountedInteger.class);
		
		System.out.println(f1.create(15));
	}

}

显示:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值