java中可以写一个方法可直接放回数组。

    1. package com.package16;
    2. import java.util.Arrays;
    3. import java.util.Random;
    4. public class IcGream {
    5. static final String[] FLAVORS = {"Chocolate", "Strawberry", "Vanilla Fudge Swirl",
    6. "Mint Chip", "Mocha Almond Fudge", "Rum Raisin",
    7. "Praline Cream", "Mud Pie"};
    8. private static Random random=new Random(47);
    9. public static String[] getFlavors(int n){
    10. if (n>FLAVORS.length) {
    11. throw new RuntimeException("你输入上读过长");
    12. }
    13. String []result =new String[n];
    14. boolean [] picked=new boolean[FLAVORS.length];
    15. for (int i = 0; i <n ; i++) {
    16. int t;
    17. do {
    18. t = random.nextInt(FLAVORS.length);//随机生成一个数字
    19. }while(picked[t]);//根据picked数组的来判断是否要向下执行,为true则不执行,继续生成t
    20. result[i] = FLAVORS[t];//数组赋值
    21. picked[t] = true;//赋值过的数组为true则次生成该数组就要返回继续生成数组索引值t
    22. }
    23. return result;
    24. }
    25. public static void test(int n,int length){
    26. for (int i = 0; i <n ; i++) {
    27. System.out.println(Arrays.toString(getFlavors(length)));
    28. }
    29. }
    30. public static void main(String[] args) {
    31. test(3,5);
    32. }
    33. }
    1. 该程序用于每次生成指定长度的数组。这里用do while的好处就是保证了会先生成数组的索引,在去添加数组。同时添加过的数组被picked数组标记为true这样等到下次在生成同样的索引时因为picked数组对应的元素为true所以会再次去随机产生索引,这样就保证了产生数组的不重复性。