This Java tip is about, how to reverse an array in Java, mostly primitive
types e.g. int, long, double and String arrays. Despite
of Java’s rich Collection API, use of array is quite common, but standard JDK
doesn’t have great utility classes for Java. It’s difficult to convert between
Java Collection e.g. List,
Set
to primitive arrays. Java’s array utility class java.util.Arrays, though
offers some the critical functionalities like comparing
arrays in Java and support
to print arrays, It lacks a lot of common features, such as combining
two arrays and reverse primitive or object array.
Thankfully, Apache commons-lang, an open-source library from Apache software foundation offers one interesting class ArrayUtils, which can be used in conjunction with java.util.Arrays class to play with both primitive and object array in Java.
This API offers conveniently overloaded method to reverse different kinds of array in Java e.g. int, double, float, log or Object arrays. On a similar note, you can also write your own utility method to reverse Array in Java, and this is even a good programming question.
For production usage, I personally prefer tried and tested library methods instead of reinventing the wheel. Apache commons-lang fits the bill, as it offers other convenient API to complement JDK. In this Java tutorial, we will reverse int and String array in Java using ArrayUtils to show How to reverse primitive and object array in Java.
Thankfully, Apache commons-lang, an open-source library from Apache software foundation offers one interesting class ArrayUtils, which can be used in conjunction with java.util.Arrays class to play with both primitive and object array in Java.
This API offers conveniently overloaded method to reverse different kinds of array in Java e.g. int, double, float, log or Object arrays. On a similar note, you can also write your own utility method to reverse Array in Java, and this is even a good programming question.
For production usage, I personally prefer tried and tested library methods instead of reinventing the wheel. Apache commons-lang fits the bill, as it offers other convenient API to complement JDK. In this Java tutorial, we will reverse int and String array in Java using ArrayUtils to show How to reverse primitive and object array in Java.
Reverse int and String array in Java - Example
Here is the code example to reverse any array in Java. We have declared
two arrays, iArray which is an int array and sArray which
stores String objects. We have also included commons-lang-2.6.jar to use org.apache.commons.lang.ArrayUtils class to
reverse Array in Java. As discussed in our last post How
to print array element in Java, We are using Arrays.toString() to print
content of array.
import java.util.Arrays; import org.apache.commons.lang.ArrayUtils; /** * * Java program to reverse array using Apache commons ArrayUtils class. * In this example we will reverse both int array and String array to * show how to reverse both primitive and object array in Java. * * @author */ public class ReverseArrayExample { public static void main(String args[]) { int[] iArray = new int[] {101,102,103,104,105}; String[] sArray = new String[] {"one", "two", "three", "four", "five"}; // reverse int array using Apache commons ArrayUtils.reverse() method System.out.println("Original int array : " + Arrays.toString(iArray)); ArrayUtils.reverse(iArray); System.out.println("reversed int array : " + Arrays.toString(iArray)); // reverse String array using ArrayUtis class System.out.println("Original String array : " + Arrays.toString(sArray)); ArrayUtils.reverse(sArray); System.out.println("reversed String array in Java : " + Arrays.toString(sArray)); } } Output: Original int array : [101, 102, 103, 104, 105] reversed int array : [105, 104, 103, 102, 101] Original String array : [one, two, three, four, five] reversed String array in Java : [five, four, three, two, one]
That's all on How to reverse Array in Java. In this Java program, we have seen examples to reverse String and int array
using Apache commons ArrayUtils class. By the way, there are a couple
of other ways to reverse array as well, e.g. by converting
Array to List and then using Collections.reverse() method or
by using brute force and reverse array using an algorithm. It depends upon, which
method you like. If you are doing practice and learning Java, try to do this
exercise using loops.
Related Java Programming tutorials from Javarevisited Blog
17 comments :
Hi Javin gr8 article but if we go by the way of java..then this thing can also be achieved..
You can reverse an array like this:
public void reverse(Object [] a){
for(int i = 0; i < a.length / 2; i++){
Object temp = a[i]; // swap using temporary storage
a[i] = a[a.length - i - 1];
a[a.length - i - 1] = temp;
}
}
It's worthy to note that it doesn't matter if the array length is an odd number, as the median value will remain unchanged. I have to admit that I haven't tested this but it should work.
For now please check the following program..http://ideone.com/3qqRAm
disappointed. i expected that you would provide algorithm for this. but you ended up in using open source library method.
public void swap(int[] arr,int a,int b){
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
public int[] reverseArray(int[] arr){
int size=arr.length-1;
for(int i=0;i<size;i++){
swap(arr,i,size--);
}
return arr;
}
/* let s1 and s2 be the two string that we have to compare.
we'll insert every character of the first string into a hashmap.
the character will be the key, whereas, the frequency of the character will be the value */
Hashmap hm = new Hashmap();
count = 1;
for (i=0; i1)
{
val--;
hm.put(j,val);
}
else
{
hm.remove(j);
}
else
{
System.out.println("Not anagrams");
}
}
if (hm.isEmpty())
{
System.out.println("Anagrams");
}
else
{
System.out.println("Not anagrams");
}
Disappointing...... Was looking for an algorithm.
Agree, bad answer.
It's better to write something like this:
void reverse(int[] arr) {
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
Agree, bad answer.
It's better to write something like this:
void reverse(int[] arr) {
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
this doesn't work
Read more: http://javarevisited.blogspot.com/2013/03/how-to-reverse-array-in-java-int-String-array-example.html#ixzz4jMYu3XQ5
public class Nevermind
{
public static void main (String[] args) {
int[] array = {1,2,3,4,5,6,7,8,9,10};
for( int i : array ){ System.out.println("Before: "+i); }
array = reverse(array);
for( int i : array ){ System.out.println("After: "+i); }
}
static int[] reverse (int[] a) {
int index = a.length-1;
int first = 0;
for (int i = first; i < index; i++){
int temp = a[index];
a[index] = a[first];
a[first] = temp;
first += 1;
index -= 1;
}
return a;
}
}
public class SwapInPlace {
public static int[] reverseInPlace(int arr[]) {
int l=0;
int high=arr.length-1;
int mid=(l+high)/2;
int len=high;
for(int i=0;i<=mid;i++) {
if(high%2==0) {
if(i<mid) {
int temp=arr[i];
arr[i]=arr[len];
arr[len]=temp;
len--;
}
}
if(high%2!=0) {
int temp=arr[i];
arr[i]=arr[len];
arr[len]=temp;
len--;
}
}
return printArray(arr);
}
public static int[] printArray(int array[]) {
for(int i=0;i<array.length;i++) {
System.out.print(array[i]+" ");
}
System.out.println();
return array;
}
public static void main(String args[]) {
int array[]= {1,3,5,4,2};
reverseInPlace(array);
int array1[]= {1,2,3,4,5,6};
reverseInPlace(array1);
}
}
/**
* Program to reverse an array in place in Java.
* Works both when array size is odd and even :)
* @author: Kennedy
*/
import java.util.Arrays;
public class reverseArrayInPlace
{
public static int [] arr;
public static int a =0;
public static int b = 0;
//method to swap two values
public static void swap(int[] arr,int a,int b)
{
//swap two values a & b
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
//method to reverse array values
public static int[] reverseArray(int[] arr)
{
//decrement the array size
int size=arr.length-1;
/**As long as current first index is less than array size swap current index with current last index
*/
for(int i=0;i<size;i++)
{
swap(arr,i,size--);
}
return arr;
}
public static void main(String []args)
{
//create array
int [] arr = {3,5,7,9,11,13,15,17,19};
//print original array
System.out.println("Original Array:" + " " + Arrays.toString(arr));
//call reverse method
reverseArray(arr);
//print reversed array
System.out.println("Reversed Array:" + " " + Arrays.toString(arr));
}
}
OUTPUT:
$javac reverseArrayInPlace.java
$java -Xmx128M -Xms16M reverseArrayInPlace
Original Array: [3, 5, 7, 9, 11, 13, 15, 17, 19]
Reversed Array: [19, 17, 15, 13, 11, 9, 7, 5, 3]
public class ReverseArray {
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6 };
reverse(arr);
}
static void reverse(int[] arr) {
int size = (arr.length) / 2;
int count = 0;
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
count++;
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
if (count == size)
break;
}
System.out.println(Arrays.toString(arr));
}
}
Good job Tapan, nice
easy way to reverse array
public class Reversearr {
public static void main(String[] args) {
Integer ar[]= {1, 1, 2, 3, 5, 5, 7, 9, 9, 9};
for(int i=ar.length-1; i>=0;i--) {
System.out.println(ar[i]);
}
}
}
@Unknown, this is not reversing the array but printing the array in reverse order. You need to return array itself where elements are in reverse order of given array.
public class bubbleSort {
public static void main(String[] args) {
int[] values = {32, 1,5, 9 ,90,16};
int[] values2 = {32, 1,5, 9 ,90,16};
int[] result = bubbleSortAsc(values);
int[] result2 = bubbleSortDes(values2);
System.out.println("ascending");
for(int value : result) {
System.out.println(value);
}
System.out.println("descending");
for(int value : result2) {
System.out.println(value);
}
}
public static int[] bubbleSortAsc(int[] list) {
int temp = 0;
int n = list.length;
for(int i=0; i < n; i++) {
for(int j=1; j < n; j++) {
if(list[j - 1] > list[j]) {
//swap
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}
return list;
}
//descending sort
public static int[] bubbleSortDes(int[] list) {
int temp = 0;
for(int i=0; i < list.length; i++) {
for(int j=0; j < list.length; j++) {
if(list[i] > list[j]) {
//swap
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
}
I will use temp method use this function to reverse array which takes tow parameters int say (arr[]) and size of the array say (n).
this function reverse array and store it in another array.
inside function new array (arr, the size of the array ) is initilized.
the array is iterated from the first element and each element arr [] is placed in the new array from the back.
Public static int reverse (int arr[] , int n) {
int b = new int [n] ;
int j = n;
for(int i = 0; i < n; i ++) {
b[j - 1] = arr[i];
j = j -1;
}
System. out. println("the reverse array: /n" ) ;
for(Int K =0; k < n; k++) {
System. Out. println(b[k] );
}
return j;
}
public static void main(String args[] ) {
int odd = {10, 20, 30, 40, 50} ;
odd. reverse (odd , odd. length) ;
}
sir we want use the manual method but you have used is actually counted in library
I had solved using swaps array like this : 1- this function to reverse the array in less number of swaps
2- this function to reverse array it self the first element swaps with the last element
3- and the second element swap with the last second element and so on
4- for instance consider array [ 1, 2, 3, n , n - 1 , n - 2] we swap 1 with n and 2 with n - 1 and 3 with n - 2 and so on
public static int swap (int a[], int n) {
int i , k , t;
for(i = 0; i< n /2; i++) {
t = a[i] ;
a[i] = a[i - n - 1] ;
a[i - n - 1] = t;
}
System. out. println ("the reverse array is : /n" ) ;
for (K = 0; k< n; k++) {
System.out.println (a[k]);
}
return k;
}
public static void main (String args []) {
int odd [] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
odd. swap (odd, odd. length) ;
}
Post a Comment