zoukankan      html  css  js  c++  java
  • 从头认识java-15.1 填充容器(2)-利用Collection的addAll方式

    接着上一章节,我们继续介绍填充容器。

    这一章节我们结束还有一种填充容器的方式: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进去。


    总结:这一章节展现了还有一种填充容器的方式。


    这一章节就到这里,谢谢。

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

    文件夹




  • 相关阅读:
    寻找完全数(C++)
    莱布尼兹三角形(C++)
    简单的素数问题(C++)
    ubuntu17.04下安装LNMP
    ubuntu下连接mysql出现Access denied for user 'rose'@'localhost' (using password: NO)的解决方法
    快速理解面向对象的PHP编程--基础篇
    百度电面总结
    操作系统基础知识
    快速理解C语言指针
    新手学习MongoDB的基本命令
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/7256122.html
Copyright © 2011-2022 走看看