從頭認識java-15.1 填充容器(2)

來源:互聯網
上載者:User

從頭認識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進去。


總結:這一章節展現了另一種填充容器的方式。


這一章節就到這裡,謝謝。

-----------------------------------

目錄




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.