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

前端 未结 6 1435
别跟我提以往
别跟我提以往 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:31

    Let say you have an array:

    String[] arrayOne = new String[]{"A","B","C","D","E"};
    

    Now you want to place the C at index 0 get the C in another variable

    String characterC = arrayOne[2];
    

    Now run the loop like following:

    for (int i = (2 - 1); i >= 0; i--) {
    
                arrayOne[i+1] = arrayOne[i];
            }
    

    Above 2 is index of C. Now insert C at index for example on 0

    arrayOne[0] = characterC;
    

    Result of above loop will be like that:

    arrayOne: {"C","A","B","D","E"}
    

    The end, we achieve our goal.

提交回复
热议问题