接着上一章节,我们继续介绍填充容器。
这一章节我们结束另一种填充容器的方式:addAll
例子:
package com.ray.ch15; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; public class Test { public static void main(String[] args) { MyCollection<String> myCollection = new MyCollection<String>( new MyGenerator(), 25);//在构造器填充 System.out.println(Arrays.toString(myCollection.toArray())); LinkedHashSet<String> set = new LinkedHashSet<String>(myCollection); System.out.println(Arrays.toString(set.toArray())); set.clear(); set.addAll(myCollection);//另一种方式 System.out.println(Arrays.toString(set.toArray())); } } interface Generator<T> { T next(); } class MyCollection<T> extends ArrayList<T> { private static final long serialVersionUID = 1L; public MyCollection(Generator<T> generator, int count) { for (int i = 0; i < count; i++) { add(generator.next()); } } } class MyGenerator implements Generator<String> { private String strPool = "The annual expansion rate for " + "industrial output will be around 6 percent this year, " + "well below this year's GDP growth, which is likely to be " + "about 7 percent, the Ministry of Industry and Information " + "Technology said, adding that such a situation was happening " + "for the first time in nearly two decades."; private int index = 0; @Override public String next() { return strPool.split(" ")[index++]; } }
[The, annual, expansion, rate, for, industrial, output, will, be, around]
[The, annual, expansion, rate, for, industrial, output, will, be, around]
[The, annual, expansion, rate, for, industrial, output, will, be, around]
我来解释一下上面的代码,有几个需要注意的地方:
(1)上面继续前几个篇幅所提到的生成器,我们通过泛型生成器来生成相关的对象。这种方式创建的对象具备灵活性,不像系统提供的nCopy方法,只能创建单一的对象。
(2)创建一个自己的容器(继承Arraylist),它是用来装载生成器创建的对象,继承某个容器,可以方便的在构造器里面调用add方法,也具备容器的特性
(3)在main方法里面展现了两种填充容器的方式,一个是直接在构造器里面添加,一个是使用addAll方法,这两种方法都是接收Collection类型的容器,因此我们无论生成什么的容器,都可以add进去。
总结:这一章节展现了另一种填充容器的方式。
这一章节就到这里,谢谢。
-----------------------------------
目录