從頭認識java-15.1 填充容器(2)
接著上一章節,我們繼續介紹填充容器。
這一章節我們結束另一種填充容器的方式: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 myCollection = new MyCollection(new MyGenerator(), 25);//在構造器填充System.out.println(Arrays.toString(myCollection.toArray()));LinkedHashSet set = new LinkedHashSet(myCollection);System.out.println(Arrays.toString(set.toArray()));set.clear();set.addAll(myCollection);//另一種方式System.out.println(Arrays.toString(set.toArray()));}}interface Generator {T next();}class MyCollection extends ArrayList {private static final long serialVersionUID = 1L;public MyCollection(Generator generator, int count) {for (int i = 0; i < count; i++) {add(generator.next());}}}class MyGenerator implements Generator {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;@Overridepublic 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進去。
總結:這一章節展現了另一種填充容器的方式。
這一章節就到這裡,謝謝。
-----------------------------------
目錄