java打乱数组
在其他博客上看过一个写打乱数组的,写了三个思路,前两个是来硬的,第三个说借用C写法,其实大可不必借用,写JAVA有思路就好,这里不用比较的方法(那个方法不能算真正的打乱数组),遵循大道至简,这是第四种思路,以下:
public static void main(String[] args) { String st="hello world"; char[] cs = st.toCharArray(); Random rd=new Random(); int [] ir=new int[cs.length]; for(int i=0;i<cs.length;i++){ ir[i]=rd.nextInt(cs.length); } for(int i=0;i<cs.length;i++){ Object t=cs[ir[i]]; cs[ir[i]]=cs[i]; cs[i]=(char) t; } System.out.println(Arrays.toString(cs)); }