What is the Simplest Way to Reverse an ArrayList?

前端 未结 10 1014
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 18:10

What is the simplest way to reverse this ArrayList?

ArrayList aList = new ArrayList<>();

//Add elements to ArrayList object
aList.add(\         


        
10条回答
  •  忘掉有多难
    2020-11-28 18:16

    Solution without using extra ArrayList or combination of add() and remove() methods. Both can have negative impact if you have to reverse a huge list.

     public ArrayList reverse(ArrayList list) {
    
       for (int i = 0; i < list.size() / 2; i++) {
         Object temp = list.get(i);
         list.set(i, list.get(list.size() - i - 1));
         list.set(list.size() - i - 1, temp);
       }
    
       return list;
     }
    
        

    提交回复
    热议问题