Java 数组去重
作者:互联网
第一种:
public class RomPriArr {
public static void main(String[] args) {
int[]arr={1,2,3,4,5};
Random rd=new Random();
int[]indexes=new int[arr.length];
for (int i = 0; i <indexes.length ; i++) {
indexes[i]=-1;
}
int index=rd.nextInt(5);
int count=0;
boolean flag;
while (count<5) {
flag=true;
for (int i = 0; i < indexes.length; i++) {
if (indexes[i]==index) {
flag = false;
break;
}
//flag=true;
}
if (flag){
indexes[count++]=index;
}
index=rd.nextInt(5);
}
for (int i = 0; i <arr.length; i++) {
System.out.print(arr[indexes[i]]+" ");
}
}
}
第二种:
public class RomPriArr {
public static void main(String[] args) {
int[]arr={1,2,3,4,5};
Random rd=new Random();
int[]indexes=new int[arr.length];
for (int i = 0; i <indexes.length ; i++) {
indexes[i]=-1;
}
for (int i = 0; i <arr.length ; i++) {
indexes[i]=rd.nextInt(arr.length);
for (int j = 0; j <i ; j++) {
if (indexes[j]==indexes[i]){
i--;
}
}
}
for (int i = 0; i <arr.length ; i++) {
System.out.print(arr[indexes[i]]+" ");
}
}
}
标签:index,arr,Java,int,indexes,rd,flag,数组 来源: https://blog.csdn.net/sungancd/article/details/114731983