Java reverse array list

3 Methods to Reverse an Array in Java

To implement array reverse in Java Programming, the array size and thereafter the array elements have to be entered by the user. In the next step, the array elements are swapped. A variable (temp) of the same type is created for placing the first element in variable temp, then the element coming last is placed in the first, temp is placed in the last, and so forth – the process continues till the entire array is reversed.

In Java, mostly primitive types of arrays — int, long, string and double arrays – are required to be reversed for the purpose of specific codes. Apache commons lang, which is an open source library attributed to the Apache software foundation, provides class ArrayUtils. This interesting class is used in association with the java.util.Arrays class for playing with object and primitive arrays in Java. The API provides easy-to-use overloaded methods for reversing different types of arrays in Java – be it int, log, double, float or object arrays.

Read on to know about this and other methods pertaining to how to reverse an array in java – the right way.

Reverse an Array in JavaHow to Reverse Array in Java with Examples

There are many methods to reverse an array in Java. You may consider writing a function on your own that loops across the array and keep swapping all the elements until the full array is sorted. In another method of array reverse in Java, an array can be converted into an ArrayList, after which a specific code can be used for reversing the ArrayList. Yet another method of array reverse in Java comprises of using the Apache Commons ArrayUtils.reverse() program for the sake of reversing any kind of Java array. This method can be overloaded for the cause of reversing short, long, int, byte, float, double or string type arrays. Users may like to implement any method to reverse an array in java as per their choice and nature of the array in the reckoning.

Method 1: Reverse Array in Place

In this simple means of reversing a Java array, the algorithm is made to loop over the array and keeps swapping the elements until the midpoint is reached. As no additional buffers are used, this method of reversing an array in Java is also referred to as an array in-place.

Читайте также:  Java частичное совпадение строк

The time complexity of the above algorithm is O(n/2). In other words, it is O(N) as the iteration across the loop takes place till its midpoint only. This method provides an ideal solution for interviewees as the remaining two methods are apt for practical purposes.

Method 2 — Using an ArrayList

This particular method of array reverse in Java converts the given array into an ArrayList and then utilizes the Collections.reverse() method that takes up the items in the list and reverses the elements in linear time. Arrays of int, string or other types can be reversed with the help of this method.The following example depicts a reversal of a string type array in Java:

//Simple Java Program to reverse a string array import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ArrayReverse < public static void main(String args[]) < String[] arrayColor = ; System.out.println("Array Before: " + Arrays.toString(arrayColor) ); List arrayNewColor = Arrays.asList(arrayColor); Collections.reverse(arrayNewColor); String[] reversed = arrayNewColor.toArray(arrayColor); System.out.println("Array Reverse: " + Arrays.toString(reversed) ); > >

Array Before: [Red, Green, Blue, Orange, Yellow]

Array Reverse: [Yellow, Orange, Blue, Green, Red]

As is evident from the output provided above, the original order of elements has been reversed in the final array as returned by the toArray() method of the List class.

Method 3 — By using ArrayUtils.reverse()

Apache commons refers is a collection of numerous utility libraries used for effective Java development. This library is often added by default by coders to their projects with a view of complementing JDK. The Apache Commons Lang offers class ArrayUtils that comprises of overloaded reverse() methods for the cause of reversing int, float as well as object type arrays in Java. This particular method reverses any given array in its place; in other words, a new array is not created for the purposes of array reverse in the Java code.

The following code will aptly depict this method:

import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; public class Byarrayutilis < public static void main(String args[]) < String[] arraycolor = ; System.out.println("Array before: " + Arrays.toString(arraycolor)); ArrayUtils.reverse(arraycolor); System.out.println("Array after: " + Arrays.toString(arraycolor)); > >

Array Before: [Red, Green, Blue, Orange, Yellow]

Array Reverse: [Yellow, Orange, Blue, Green, Red]

The ArrayUtils class belongs to Apache Commons Lang. Commons-lang3-3.4.jar has to be added into the application’s class path for this method to take place. Alternatively, in the case of Maven is being used then the following dependency has to be included in the pom.xml file.

 org.apache.commons commons-lang3 3.4 

How do I Print reverse of an array in Java?

At the very onset, values have to be provided to the array that needs to be reversed in Java.

Next, the loop counter has to be initialized. This initialization process can take place from within the loop structure. The loop can be defined as:

for (int i = var.length - 1; i >= 0; --i)

The output is 321 that will be printed to the console.

Читайте также:  Absolute function in javascript

The above-mentioned methods go a long way in helping coders reverse int & String array in Java. Reverse array in Java can be appropriately implemented in line with the above three methods. In case you have to answer an interview question pertaining to a java program to reverse an array then use the in-place algorithm. The others methods include usage of the ArrayList class and the utility method ArrayUtils.reverse() belonging to the Apache commons lang library. Choose the method that applies to your reverse array in java programming needs in the best possible way!

  • What is Java?
  • Java Training Tutorials for Beginners
  • How Java Programming Works
  • Polymorphism in Java
  • Abstract Class vs Interface
  • Decimal to Binary
  • Comparable vs Comparator
  • Difference between AWT and Swing with Comparison Chart
  • Remove Duplicates from Array
  • Difference between Error and Exception
  • Difference between Array and ArrayList
  • Java Calculator
  • Difference between Throw and Throws
  • Association, Aggregation and Composition in Java
  • Error Could not find or load main class
  • Difference between SDM and JSPM
  • Java Program using Eclipse IDE
  • Java Multithreading Interview Questions
  • Rock Paper Scissors Java
  • Java Interview Questions

Источник

How to reverse ArrayList in Java with Example

You can reverse ArrayList in Java by using the reverse() method of java.util.Collections class. This is one of the many utility methods provided by the Collections class e.g. sort() method for sorting ArrayList. The Collections.reverse() method also accepts a List, so you not only can reverse ArrayList but also any other implementation of List interface e.g. LinkedList or Vector or even a custom implementation. This method has a time complexity of O(n) i.e. it runs on linear time because it uses ListIterator of the given list. It reverses the order of an element in the specified list.

By the way, you cannot reverse an ArrayList using this method if the specified ArrayList or it’s ListIterator doesn’t support set() operation. It switches between two algorithms depending upon the size of List or if List implements RandomAccess interface like ArrayList.

If a number of elements in List are less than REVERSE_THRESHOLD , which is equal to 18 then it uses for loop for swapping elements otherwise it uses list iterator. If you want to learn more about how the reverse() method of Collections works, you can see it’s code from JDK itself or in the next section.

By the way, this is a typesafe generic method and you can use it to reverse Integer, String, Float or any kind of List in Java. You can also see the classic book Core Java Volume 1 — Fundamentals by Cay S. Horstmann to learn more about key classes of the Java Development Kit.

Читайте также:  Revit api python уроки

Java Program to Reverse an ArrayList in Java

Here is my code example of reversing an ArrayList of Integer. You can see that we have added numbers on increasing order but after calling reverse() method, it prints them on decreasing order. Unlike popular misconception, Comparable or Comparator is not used while reversing ArrayList in Java. Though they are used if you want to sort Array in Java.

import java.util.ArrayList; import java.util.Collections; /** * Java program to reverse ArrayList by using Collections.reverse() * method. This method will work for any kind of ArrayList e.g. * integer list or String list, but this method will not work * for an ArrayList which doesn't support set() operation. * * @author WINDOWS 8 */ public class ArrayListReverseDemo < public static void main(String args[]) < ArrayList listOfInts = new ArrayList<>(); listOfInts.add("1"); listOfInts.add("2"); listOfInts.add("3"); listOfInts.add("4"); listOfInts.add("5"); System.out.println("Before Reversing : " + listOfInts); Collections.reverse(listOfInts); System.out.println("After Reversing : " + listOfInts); > > Output Before Reversing : [1, 2, 3, 4, 5] After Reversing : [5, 4, 3, 2, 1]

How Collections.reverse() method works in Java

Here is the code snippet from java.util.Collections class which you can use to reverse an ArrayList or any kind of List in Java. You can see that it uses set() method of List interface for swapping elements and that’s why you cannot reverse a read-only ArrayList because it doesn’t support set() operation.

ArrayList reverse Example in Java

Logic of Collections.reverse() method

Here is the logic and explanation of how the Collections.reverse() method works and how it reverse the given collection.

/** * Reverses the order of the elements in the specified list. * * This method runs in linear time. * * @param list the list whose elements are to be reversed. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the set operation. */ public static void reverse(List list) < int size = list.size(); if (size  REVERSE_THRESHOLD || list instanceof RandomAccess) < for (int i=0, mid=size>>1, j=size-1; imid; i++, j--) swap(list, i, j); > else < ListIterator fwd = list.listIterator(); ListIterator rev = list.listIterator(size); for (int i=0, mid=list.size()>>1; imid; i++) < Object tmp = fwd.next(); fwd.set(rev.previous()); rev.set(tmp); > > >

That’s all about how to reverse ArrayList in Java. Though you can always write your method to reverse an ArrayList, it won’t be much different than how you reverse an Array in Java, it’s always better to use a function from the JDK library. Why? because they are well tested for programming bugs and corner cases and they are much more optimized than you think, because of wider audiences who have used and improved them already. Let us know if you know a faster way to reverse ArrayList in Java.

Источник

Оцените статью