Swap two elements of an array given their indices. - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Swap two elements of an array given their indices.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object[] a = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        int first = 2;
        int second = 2;
        swap(a, first, second);/*from w ww.ja va  2  s  .  c o m*/
    }

    /** Swap two elements of an array given their indices.
     * 
     * @param a  the array to work on
     * @param first  the index of the first element to swap
     * @param second  the index of the second element to swap
     */
    public static void swap(Object[] a, int first, int second) {
        Object newFirst = a[second];
        a[second] = a[first];
        a[first] = newFirst;
    }
}

Related Tutorials