How to move specific item in array list to the first item

前端 未结 6 1450
别跟我提以往
别跟我提以往 2020-12-08 13:03

For example : A list

A B C D E

Given C , Switch to

C A B D E

Notice that the array size will change, some items may removed in run times

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 13:23

    This code will allow you to increase size of list, and insert elements without otherwise disturbing order of list

    private void insert(double price){
        for(int i = 0; i < keys.size(); i++){
            if(price > keys.get(i)){
                keys.add(null);
                for(int j = keys.size()-1; j > i; j--){
                    Collections.swap(keys, j, j-1);
                }
                keys.add(price);
                Collections.swap(keys, keys.size()-1, i);
                keys.remove(keys.size()-1);
                return;
            }
        }
        keys.add(price);
    }
    

提交回复
热议问题