Reyjohn Reyjohn - 1 year ago 27
Java Question

How to avoid duplicate random number and select another one in android?

I have an Arraylist and an Array of integer like this,

ArrayList<Integer> ar= new ArrayList<Integer>();
int[] number= {0,1,2,3,4,5};

Now I want to toast the integers from this array evertime I click a button with out any repeatation. After toasting every number from this array I want to toast 'Finished', my logic in onclick listener is here:

Random r = new Random();

int i1=r.nextInt(number.length-0) + 0;
Toast.makeText(getApplicationContext(), ""+i1, Toast.LENGTH_LONG).show();

Toast.makeText(getApplicationContext(), "Finished", Toast.LENGTH_LONG).show();

but this didnt come to my way, It doesnt repeat any number but if it gets a duplicate number in the second click then it is toasting finished, but I want to toast it after every number from the integer array are toasted, wat should be my modified logic?

Answer Source
ArrayList<Integer> ar= new ArrayList<Integer>();
int[] number= {0,1,2,3,4,5};
for (int i : number) {

Random r = new Random();

// repeat this part and you will never have duplicate numbers
int select = r.nextInt(ar.size());
int random = ar.get(select);