简体   繁体   中英

Kotlin index is not out of bounds using arraylist

I created an arraylist with 4 items

val myList = arrayListOf("Item1", "Item2", "Item3", "Item4")

Then I printed a random item from myList

val randomNum = Random()
val randomItem = randomNum.nextInt(myList.count())
println(myList[randomItem])

Shouldn't this fail? Once randomItem is equal to 4? Ideally what I'm asking is that randomItem is returning an int from 0-4, correct? But the arraylist index is only 0-3. Should I do -1 to randomItem? I'm just confused because the program isn't throwing an error.

See the API here Random.nextInt(int bound)

public int nextInt(int bound)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive) , drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability.

Parameters : bound - the upper bound ( exclusive ). Must be positive.

Returns : the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive) from this random number generator's sequence

So in your case, you get 0, 1, 2 or 3

The documentation explains it pretty well:

int nextInt(int bound)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive) , drawn from this random number generator's sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM