接着上一章节,我们继续介绍填充容器。
这一章节我们结束还有一种填充容器的方式: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进去。
总结:这一章节展现了还有一种填充容器的方式。
这一章节就到这里,谢谢。
-----------------------------------