Randomly select two different elements from ArrayList

Correct implementation:
Note: size must be greater than 1, otherwise there are no two

Random rand=new Random();
//[0,arrayList.size()),左闭右开
int randNumber1 =rand.nextInt(arrayList.size());

int randNumber2 =rand.nextInt(arrayList.size()-1);

if(randNumber2 >=randNumber1 ){
    
    
	randNumber2 =randNumber2 +1;
}

Wrong realization:

Random rand=new Random();
//[0,arrayList.size()),左闭右开
int randNumber1 =rand.nextInt(arrayList.size());

int randNumber2 =rand.nextInt(arrayList.size()-1);

if(randNumber2 ==randNumber1 ){
    
    
	randNumber2 =randNumber2 +1;
}

Explanation: randNumber1 is a random number, mainly because randNumber2 is different from the first number.
Suppose the number 1 is selected from [0,4), 0,1,2,3 can be selected, and the
number 2 is [0,3), 0,1,2 can be selected
, only if the number 1=2 and the number 2=2. At this time, the number 2 can be equal to 3 is
unreasonable! ! ! It's not random


Guess you like

Origin blog.csdn.net/root_zhb/article/details/107830349