Java Array Shift arrayShift(Object[] input, int shift)

Here you can find the source of arrayShift(Object[] input, int shift)

Description

Shift all objects in an array by the number of places specified.

License

Open Source License

Declaration

public static Object[] arrayShift(Object[] input, int shift) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from   w  ww  .java 2 s .  c  om
     * Shift all objects in an array by the number of places specified.
     * <p/>
     * Example:
     * Object[] array = {1, 2, 3, 4, 5}
     * array = arrayShift(array, 1);
     * array now equals {5, 1, 2, 3, 4}
     * Shift can be a positive or negative number
     * <p/>
     * Shift is not restricted to any max or min value so it could for example be linked to a counter that
     * continuously increments.
     */
    public static Object[] arrayShift(Object[] input, int shift) {
        Object[] newArray = new Object[input.length];

        for (int i = 0; i < input.length; i++) {
            int newPos = (i + shift) % input.length;

            if (newPos < 0) {
                newPos += input.length;
            }

            newArray[newPos] = input[i];
        }

        return newArray;
    }
}

Related

  1. arrayShiftArgs(int[] array, int a)
  2. shift(double[] a, int shift, double insert)
  3. shift(double[] x, int N)
  4. shift(final byte[] input, final int amount)