/**
* 书本:《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]