下面java代码的CollectionData适配器是否有用
大家讲道理
大家讲道理 2017-04-17 13:09:20
[Java讨论组]

看《java编程思想》遇到的问题:在讲容器的时候,提出一种用生成器来填充容器的方法:
代码如下:

javapublic class CollectionData<T> extends ArrayList<T>{
    public CollectionData(Generator<T> gen, int quantity){
        for(int i=0; i<quantity; i++){
            add(gen.next());
        }
    }

    public static <T> CollectionData<T> list(Generator<T> gen, int quantity){
        return new CollectionData(gen, quantity);
    }
}

class Government implements Generator<String> {
  String[] foundation = ("strange women lying in ponds " +
    "distributing swords is no basis for a system of " +
    "government").split(" ");
  private int index;
  public String next() { return foundation[index++]; }
}

public class CollectionDataTest {
  public static void main(String[] args) {
    Set<String> set = new LinkedHashSet<String>(
      new CollectionData<String>(new Government(), 15));
    // Using the convenience method:
    set.addAll(CollectionData.list(new Government(), 15));
    System.out.println(set);
  }
}

我理解这是一种适配器设计模式的应用,通过 new CollectionData(new Government(), 15)可以一次生成给定数量的某个类的对象。 但是不知道为什么要以这么一种繁琐的方式. 举个例子
我想生成10个Coffee对象..

javapublic class CopyOfCollectionDataTest {
  public static void main(String[] args) {
        Set<Coffee> set2 = new LinkedHashSet<Coffee>();
        int  i = 10;
        while(i !=0){
        set2.add(new Coffee());
        i--;
    }

觉得这段代码已经足够,如果生成其他类型的对象只需要修改Set类型参数即可呀。
所以问题是上面的CollectionData适配器是否有用?谢谢!

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号