本文共 726 字,大约阅读时间需要 2 分钟。
泛型举例。作为容器的的另一个例子。假如我们需要构建一个可以应用于各种类型的对象工具,就需要用到泛型。举例:RandomList
public class RandomList{ private ArrayList storage = new ArrayList (); private Random rand = new Random(47); public void add(T item) {//新增对象 storage.add(item); } public T select() {//获取对象 return storage.get(rand.nextInt(storage.size())); } public static void main(String[] args) {//测试 RandomList rs = new RandomList (); for (String s : ("The quick brown fox jumped over " + "the lazy brown dog").split(" ")) rs.add(s); for (int i = 0; i < 11; i++) System.out.print(rs.select() + " "); }}
转载地址:http://paofa.baihongyu.com/