随机生成char数组,没有重复的索引

时间:2018-07-07 22:50:51

标签: java android

想要在没有重复索引的char数组中生成随机字符,并将它们存储在新的ArrayList中。

ArrayList<Character> al = new ArrayList<>();
char letters[ ] = {'a', 'b', 'c', 'd', 'e'};
for(int i =0; i<letters.length; i++){
    al.add(letters[ i ]);
}
ArrayList<Character> al2 = new ArrayList<>();
Random random = new Random ();
while (al.size() > 0) {
    int randomizedNumber = random.nextInt(al.size());
    al2.add(letters[ randomizedNumber ]; //adding randomized charterer in the new ArrayList.
    al.remove(letters[ randomizedNumber ];
}

1 个答案:

答案 0 :(得分:0)

如果只想随机化数组的顺序,则可以使用Collections.shuffle

Character letters[ ] = {'a', 'b', 'c', 'd', 'e'};
ArrayList<Character> a1 = new ArrayList<>(Arrays.asList(letters));
Collections.shuffle(a1, new Random());