What is the Simplest Way to Reverse an ArrayList?

前端 未结 10 973
伪装坚强ぢ
伪装坚强ぢ 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:34

    Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:

    public ArrayList reverse(ArrayList list) {
        if(list.size() > 1) {                   
            Object value = list.remove(0);
            reverse(list);
            list.add(value);
        }
        return list;
    }
    
    
    

    Or non-recursively:

    public ArrayList reverse(ArrayList list) {
        for(int i = 0, j = list.size() - 1; i < j; i++) {
            list.add(i, list.remove(j));
        }
        return list;
    }
    
        

    提交回复
    热议问题