Java Array Reverse reverse(T[] array)

Here you can find the source of reverse(T[] array)

Description

reverse

License

Open Source License

Declaration

public static <T> T[] reverse(T[] array) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Oobium, Inc./*from w  w  w .  ja v a 2s .  c o m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Jeremy Dowdall <jeremy@oobium.com> - initial API and implementation
 ******************************************************************************/

import java.util.List;

public class Main {
    public static <T> T[] reverse(T[] array) {
        if (array != null && array.length > 1) {
            for (int i = 0; i < array.length / 2; i++) {
                swap(array, i, array.length);
            }
        }
        return array;
    }

    public static <T> List<T> reverse(List<T> list) {
        int len = list.size();
        if (list != null && len > 1) {
            for (int i = 0; i < len / 2; i++) {
                swap(list, i, len);
            }
        }
        return list;
    }

    private static <T> void swap(T[] array, int i, int len) {
        T tmp = array[i];
        array[i] = array[len - i - 1];
        array[len - i - 1] = tmp;
    }

    private static <T> void swap(List<T> list, int i, int len) {
        T tmp = list.get(i);
        list.set(i, list.get(len - i - 1));
        list.set(len - i - 1, tmp);
    }
}

Related

  1. ArraysReverse(byte[] array)
  2. getReverseOffsets(long fileLength, long position, byte[] buffer, int size)
  3. reverse(T[] array)
  4. reverse(T[] array)
  5. reverse(T[] array)
  6. reverse(T[] array)
  7. reverse(T[] originalArray)
  8. reverseArray(final T[] arr)
  9. reverseArray(Object[] arr)