1. 泛型还可以应用于匿名内部类中<br /> 列:泛型在匿名内部类中的使用。(排队场景)
    1. public interface Generator <T>{
    2. T next();
    3. }
    4. public class Generators {
    5. public static <T> Collection<T> fill(Collection<T> coll,Generator<T> gen,int n){
    6. for (int i=0;i<n;i++){
    7. coll.add(gen.next());
    8. }
    9. return coll;
    10. }
    1. package com.package15;
    2. import com.package15.coffe.Generator;
    3. import com.package15.coffe.Generators;
    4. import java.util.*;
    5. class Customer{
    6. private static long count=0;
    7. private final long id=count++;
    8. Customer(){}
    9. @Override
    10. public String toString() {
    11. return "Customer"+id;
    12. }
    13. public static Generator<Customer> generator(){
    14. return new Generator<Customer>() {
    15. @Override
    16. public Customer next() {
    17. return new Customer();
    18. }
    19. };
    20. }
    21. }
    22. class Teller{
    23. private static long coumt=1;
    24. private final long id=coumt++;
    25. Teller(){}
    26. @Override
    27. public String toString() {
    28. return "Teller"+id;
    29. }
    30. public static Generator<Teller> generator=new Generator<Teller>() {
    31. @Override
    32. public Teller next() {
    33. return new Teller();
    34. }
    35. };
    36. }
    37. public class BankTell {
    38. public static void server(Teller t,Customer c){
    39. System.out.println(t+" serves "+c);
    40. }
    41. public static void main(String[] args) {
    42. Random random = new Random(47);
    43. Queue<Customer> qurak = new LinkedList<Customer>();
    44. Generators.fill(qurak,Customer.generator(),15);
    45. List<Teller> tellers = new ArrayList<>();
    46. Generators.fill(tellers,Teller.generator,4);
    47. for (Customer customer : qurak) {
    48. server(tellers.get(random.nextInt(tellers.size())),customer);
    49. }
    50. }
    51. }