繁体   English   中英

更改 ArrayList 中元素顺序的最快方法是什么?

[英]What is the fastest way to change the order of elements in an ArrayList?

我有第一个 ArrayList:

ArrayList<Move> moves = new ArrayList<>();

并希望将元素随机重新排序为第二个:

ArrayList<Move> randomMoves = new ArrayList<>();

通常我会这样做:

    while (randomMoves.size() < moves.size()) {
    
        int index = (int) (Math.random() * moves.size());

        while (randomMoves.contains(moves.get(index))) {

            index = (int) (Math.random() * moves.size());
        }
        
        randomMoves.add(moves.get(index));
    }

但不言而喻,这是一场性能灾难(最后一个元素需要时间随机选择)......

通常这不是什么大问题,但是这段代码将在应用程序的时间关键部分执行,我对时间关键代码没有太多经验......

开导我:)

S。

您可以使用Collections.shuffle(List<?> list) list的元素。

ArrayList<Move> randomMoves = new ArrayList<>(moves);
Collections.shuffle(randomMoves);

代码的第一行创建一个包含moves元素的ArrayList<Move> randomMoves代码的第二行将randomMoves中的元素打乱。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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