Java Array Swap swap(T[] array, int indexOne, int indexTwo)

Here you can find the source of swap(T[] array, int indexOne, int indexTwo)

Description

Swaps elements in the array at indexOne and indexTwo.

License

Apache License

Parameter

Parameter Description
T Class type of the elements in the array.
array array with the elements to swap.
indexOne index of the first element to swap.
indexTwo index of the second element to swap.

Exception

Parameter Description
ArrayIndexOutOfBoundsException if the indexes are not valid indexes in the array.
NullPointerException if the array is null.

Return

the array with the specified elements at indexOne and indexTwo swapped.

Declaration

public static <T> T[] swap(T[] array, int indexOne, int indexTwo) 

Method Source Code

//package com.java2s;
/*//from ww w.j  a  v a 2  s . co  m
 * Copyright 2016 Author or Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Swaps elements in the array at indexOne and indexTwo.
     *
     * @param <T> Class type of the elements in the array.
     * @param array array with the elements to swap.
     * @param indexOne index of the first element to swap.
     * @param indexTwo index of the second element to swap.
     * @return the array with the specified elements at indexOne and indexTwo swapped.
     * @throws ArrayIndexOutOfBoundsException if the indexes are not valid indexes in the array.
     * @throws NullPointerException if the array is null.
     */
    public static <T> T[] swap(T[] array, int indexOne, int indexTwo) {

        T elementAtIndexOne = array[indexOne];

        array[indexOne] = array[indexTwo];
        array[indexTwo] = elementAtIndexOne;

        return array;
    }
}

Related

  1. swap(T[] arr, int index1, int index2)
  2. swap(T[] arr, int pos1, int pos2)
  3. swap(T[] array, int a, int b)
  4. swap(T[] array, int first_idx, int last_idx)
  5. swap(T[] array, int i, int len)
  6. swap(T[] data, int a, int b)
  7. swap(T[] elements, int i, int j)
  8. swap(T[] ts, int i, int j)
  9. swap2(double v[], int v2[], int i, int j)