Created
March 22, 2012 09:10
-
-
Save palianytsia/2157265 to your computer and use it in GitHub Desktop.
An example of how to reverse elements in the list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.examples; | |
import java.util.ArrayList; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.ListIterator; | |
/** | |
* This is utility class that contains an example of how to reverse elements in | |
* the list. You shouldn't actually implement your own reverse utility - use | |
* <code>Collections.reverse(List<?> list)</code> method instead. | |
* | |
* @author Ivan Palianytsia | |
*/ | |
public class ListReverse | |
{ | |
/** | |
* Reverses the list elements. | |
* | |
* @param <T> | |
* Type of list elements. | |
* | |
* @param list | |
* List to reverse elements in. Can't be null. | |
* | |
* @throws IllegalArgumentException | |
* If the parameter given is null. | |
*/ | |
public static <T> void reverse(List<T> list) | |
{ | |
if (list == null) | |
{ | |
throw new IllegalArgumentException( | |
"Expected an object implementing list interface - null given."); | |
} | |
ListIterator<T> headIterator = list.listIterator(); | |
ListIterator<T> tailterator = list.listIterator(list.size()); | |
for (int i = 0; i < list.size() / 2; i++) | |
{ | |
T headElement = headIterator.next(); | |
T tailElement = tailterator.previous(); | |
headIterator.set(tailElement); | |
tailterator.set(headElement); | |
} | |
} | |
public static void main(String[] args) | |
{ | |
List<String> straight = new ArrayList<String>(); | |
straight.add("Ten"); | |
straight.add("Jack"); | |
straight.add("Queen"); | |
straight.add("King"); | |
straight.add("Ace"); | |
List<Integer> primes = new LinkedList<Integer>(); | |
primes.add(1); | |
primes.add(3); | |
primes.add(5); | |
primes.add(7); | |
primes.add(11); | |
primes.add(13); | |
System.out.println(straight); | |
System.out.println(primes); | |
reverse(straight); | |
reverse(primes); | |
System.out.println(straight); | |
System.out.println(primes); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment