想要在没有重复索引的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 ];
}
答案 0 :(得分:0)
如果只想随机化数组的顺序,则可以使用Collections.shuffle
Character letters[ ] = {'a', 'b', 'c', 'd', 'e'};
ArrayList<Character> a1 = new ArrayList<>(Arrays.asList(letters));
Collections.shuffle(a1, new Random());