This example will show how to reverse the order of a given array using straight up java and apache commons ArrayUtils.reverse. This could also be accomplished by sorting the array in reverse order
Setup String [] MONTHS_OF_YEAR_BACKWARDS ;
@Before
public void setUp () {
MONTHS_OF_YEAR_BACKWARDS = new String [] {
"December" ,
"November" ,
"October" ,
"September" ,
"August" ,
"July" ,
"June" ,
"May" ,
"April" ,
"March" ,
"February" ,
"January"
};
}
Straight up Java @Test
public void reverse_elements_in_array_with_java () {
for ( int i = 0 ; i < MONTHS_OF_YEAR_BACKWARDS . length / 2 ; i ++) {
// set a temp variable for current element
String temp = MONTHS_OF_YEAR_BACKWARDS [ i ];
// find the last element - 1
int j = MONTHS_OF_YEAR_BACKWARDS . length - i - 1 ;
// set the first element to last
MONTHS_OF_YEAR_BACKWARDS [ i ] = MONTHS_OF_YEAR_BACKWARDS [ j ];
// set last to the first
MONTHS_OF_YEAR_BACKWARDS [ j ] = temp ;
}
logger . info ( Arrays . toString ( MONTHS_OF_YEAR_BACKWARDS ));
assertEquals ( "May" , MONTHS_OF_YEAR_BACKWARDS [ 4 ]);
}
Output
[ January , February , March , April , May , June , July , August , September , October , November , December ]
Apache Commons @Test
public void reverse_elements_in_array_with_apache_commons () {
ArrayUtils . reverse ( MONTHS_OF_YEAR_BACKWARDS );
logger . info ( Arrays . toString ( MONTHS_OF_YEAR_BACKWARDS ));
assertEquals ( "May" , MONTHS_OF_YEAR_BACKWARDS [ 4 ]);
}
Output
[ January , February , March , April , May , June , July , August , September , October , November , December ]
Reverse elements in array posted by Justin Musgrove on 02 February 2013
Tagged: java and java-arrays
Share on: Facebook Google+
All the code on this page is available on github:
ReverseElementsInArray.java