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