简体   繁体   中英

Choose a random element from Java.util.Deque

Usually I use the Deque for it's intended purpose but infrequently I need to choose a random element from it. I use the below code to do so, but it requires iterating through the Deque. Is there a more efficient way to do it?

Iterator<T> iterator = mDeque.iterator();
int target = mRand.nextInt(mDeque.size());
while (iterator.hasNext()) {
    if (target == 0) {
        chosenElement = iterator.next();
        break;
    } else {
        iterator.next();
        target--;
     }
 }

您可以使用ArrayDeque ,使用toArray ,然后直接使用索引(您的示例为[target]

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