Arraylist & Reverse, an Array List in #Java

Jahid Momin
2 min readJun 3, 2022
jahid momin.
created by jahid momin

Java ArrayList class uses a dynamic Array for storing the elements.

Some important points of array list :

1 ] No Size Limit.

2] Flexible than Traditional Array

3] ArrayList in Java can have the duplicate elements also.

4] It implements the List interface.

5] The ArrayList maintains the insertion order internally.

6] Array List class maintains insertion order.

7] Array List allows random access because the array works on an index basis.

Let's come to the problem :

Our Arraylist :

List<Integer> noList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));

Expected Arraylist :

List<Integer> expectedList = new ArrayList<>(Arrays.asList(7, 6, 5, 4, 3, 2, 1));

Using Collections.reverse Method

List<Integer> noList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); Collections.reverse(noList);

but in some case we dont want to change original array list so what will we do ?

we will take new object and store this array list in that and then will do reverse operation.

List<Integer> originalList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));

List<Integer> newList = new ArrayList<>(originalList); Collections.reverse(newList);

Second way to do reverse using recursion .

public class DemoReverseList {

public static <T> void reverseWithRecursion(List<T> list) {

if (list.size() > 1) {

T value = list.remove(0);

reverseWithRecursion(list);

System.out.println(value);

list.add(value);

}

}

public static void main(String[] args) {

List<Integer> List = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));

DemoReverseList.reverseWithRecursion(List);

System.out.println(List);

}

}

Thanks for reading.

Keep sharing.

--

--

Jahid Momin

Team Lead | Sr Software Engineer | Spring boot | Microservices | JavaScript | CodeIgniter | HTML | CSS | ReactJS | NextJS | Youtuber | Writer