泛型还可以应用于匿名内部类中<br /> 列:泛型在匿名内部类中的使用。(排队场景)
public interface Generator <T>{ T next();}public class Generators { public static <T> Collection<T> fill(Collection<T> coll,Generator<T> gen,int n){ for (int i=0;i<n;i++){ coll.add(gen.next()); } return coll; }
package com.package15;import com.package15.coffe.Generator;import com.package15.coffe.Generators;import java.util.*;class Customer{ private static long count=0; private final long id=count++; Customer(){} @Override public String toString() { return "Customer"+id; } public static Generator<Customer> generator(){ return new Generator<Customer>() { @Override public Customer next() { return new Customer(); } }; }}class Teller{ private static long coumt=1; private final long id=coumt++; Teller(){} @Override public String toString() { return "Teller"+id; } public static Generator<Teller> generator=new Generator<Teller>() { @Override public Teller next() { return new Teller(); } };}public class BankTell { public static void server(Teller t,Customer c){ System.out.println(t+" serves "+c); } public static void main(String[] args) { Random random = new Random(47); Queue<Customer> qurak = new LinkedList<Customer>(); Generators.fill(qurak,Customer.generator(),15); List<Teller> tellers = new ArrayList<>(); Generators.fill(tellers,Teller.generator,4); for (Customer customer : qurak) { server(tellers.get(random.nextInt(tellers.size())),customer); } }}