hoding object-1

来源:互联网 发布:淘宝店卖家界面 编辑:程序博客网 时间:2024/05/18 01:02
  • 自定义生成器类,在调用next方法之后将循环添加内容(包括数组,集合),并返回集合。
  • search “awesome” for talent code pieces
package test;import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;class Generator{    int k = 0;      public String next(){//      int k = 0;  //一开始将写在了方法里面,导致k一直初始化为0,所以打印出来的全都是a        switch(k){            default:            case 0 : k++; return "a";              case 1 : k++; return "b";              case 2 : k++; return "c";              case 3 : k++; return "d";              case 4 : k++; return "e";              case 5 : k = 0; return "f";    //Awesome: reset the k to 0        }    }    public void fillToArray(String[] a){        for(int i=0; i<a.length; i++)            a[i] = next();    }    public Collection fillToCollection(Collection<String> col, int n){        for(int i=0; i<n; i++) col.add(next());        return col;    }}public class Test {    public static void main(String[] args) {        Generator gen = new Generator();        String[] str = new String[10];        gen.fillToArray(str);        for(int i=0; i<str.length; i++) System.out.print(str[i]+" ");        System.out.println();        System.out.print(gen.fillToCollection(new ArrayList(), 10));  //不用指定大小        System.out.println();        System.out.print(gen.fillToCollection(new HashSet(), 10));    }}/* result:    a b c d e f a b c d     [e, f, a, b, c, d, e, f, a, b]    [a, b, c, d, e, f]*/
0 0
原创粉丝点击