Swap array element java

What is ArrayUtils.swap in Java?

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

swap is a static method of the ArrayUtils class that swaps the positions of two elements in an array.

Characteristics

  • The swap operation is in-place in nature, i.e., the modification is done to the original array.
  • Negative indices are promoted to zero.
  • The swap operation is not applied for the following conditions:
    • The input array is null .
    • The input indices lead to overflow.
    • The input array is empty.

    Syntax

    public static void swap(final int[] array, final int offset1, final int offset2) 

    Parameters

    • final int[] array : holds the array with the elements that need to be swapped.
    • final int offset1 : holds the index of the first element to swap.
    • final int offset2 : holds the index of the second element to swap.

    Return value

    The method doesn’t return anything, as the modification is applied to the original array passed as an argument.

    Add the Apache Commons Lang package

    ArrayUtils is defined in the Apache Commons Lang package. To add Apache Commons Lang to the Maven Project, add the following dependency to the pom.xml file.

     org.apache.commons commons-lang3 3.12.0  

    For other versions of the commons-lang package, refer to the Maven Repository.

    How to import ArrayUtils

    You can import the ArrayUtils class as follows.

    import org.apache.commons.lang3.ArrayUtils; 

    Code

    Example 1

    Let’s say we want to swap the elements at offsets (position) 1 & 4.

    Application of the swap function will result in the following array: [5, 2, 3, 4, 1] .

    The element at position 1, i.e., 2 , is swapped with the element at position 4, i.e., 5 .

    Example 2

    Let’s say we want to swap the elements at offsets (position) -4 & 4.

    Application of the swap function will result in the following array: [5, 2, 3, 4, 1] .

    The first negative index will be changed to 0 (zero). Hence, the element at position 0, i.e., 1 , is swapped at position 4, i.e., 5 .

    Источник

    Swap two elements in an array in Java

    In this blog, you will see simple logic to swap the elements of the array, and also you can learn about Java.util.Collections Swap method.

    Simple Swapping logic in Java

    public class SwapElementsExample < public static void main(String[] args) < String[] arr = ; System.out.println("Array before Swap" + "\n"); for (String element : arr) < System.out.println(element); >//Simple Swapping logic String temp = arr[1]; arr[1] = arr[2]; arr[2] = temp; System.out.println("\n" + "Array after Swap" + "\n"); for (String element : arr) < System.out.println(element); >> >
    Output Array before Swap First Second Third Fourth Array after Swap First Third Second Fourth

    Collections.swap()

    This method is used to swap the item to the specified positions within the list.

    Syntax

    public static void swap(List list, int a, int b);

    list – the specified list where the elements are to be swapped

    a – Index of the element to be swapped.

    b – index of another element to be swapped

    If the a or b is out of the range of the list, then the method throws the IndexOutOfBoundsException.

    Example

    import java.util.ArrayList; import java.util.Collections; public class SwapElementsExample < public static void main(String[] args) < ArrayListarrList = new ArrayList(); //adding the elements in Array List arrList.add("1. Anupam Mittal"); arrList.add("2. Aman Gupta"); arrList.add("3. Namita Thapar"); arrList.add("4. Ashneer Grover"); arrList.add("5. Peyush Bansal"); System.out.println("Current ArrayList " + arrList); System.out.println("\n" + "-- Elements in Arraylist before swap --"); for (String element : arrList) < System.out.println(element); >//using the swap method Collections.swap(arrList, 1, 4); System.out.println("\n" + "Using Collections.swap(arrList, 1, 4)"); System.out.println("\n" + "Current ArrayList " + arrList); System.out.println("\n" + "-- Elements in Arraylist after swap --"); for (String element : arrList) < System.out.println(element); >> >
    Output Current ArrayList [1. Anupam Mittal, 2. Aman Gupta, 3. Namita Thapar, 4. Ashneer Grover, 5. Peyush Bansal] -- Elements in Arraylist before swap -- 1. Anupam Mittal 2. Aman Gupta 3. Namita Thapar 4. Ashneer Grover 5. Peyush Bansal Using Collections.swap(arrList, 1, 4) Current ArrayList [1. Anupam Mittal, 5. Peyush Bansal, 3. Namita Thapar, 4. Ashneer Grover, 2. Aman Gupta] -- Elements in Arraylist after swap -- 1. Anupam Mittal 5. Peyush Bansal 3. Namita Thapar 4. Ashneer Grover 2. Aman Gupta

    That’s enough for a quick overview of Swapping elements of an array in Java.
    Thank you

    Источник

    Swap Arrays in Java

    Swap Arrays in Java

    1. Use Numeric Operators to Swap Two Arrays in Java
    2. Use Bitwise Operators to Swap Two Arrays in Java
    3. Use Collections.swap() to Swap Two Elements of an Array in Java

    In this article, we will look into different approaches to swap two arrays in Java. Instead of using a third variable to swap two arrays, we can use arithmetic and bitwise Operators.

    Use Numeric Operators to Swap Two Arrays in Java

    Here in the code given below, we have two arrays, a and b , which hold int type values. The length of the two arrays is the same.

    We use arithmetic operators to swap a and b . For the first iteration, we have i equal to 0 and condition (i<2) , so that the arithmetic statements inside the loop will be executed until the condition fails.

    a[0] = a[0] - b[0] = 5-4 = 1  b[0] = a[0] + b[0] = 1+4 = 5  a[0] = GetAbsoluteValue(a[0] - b[0])= 1-5 = GetAbsoluteValue(-4) = 4 

    Math.abs() returns the absolute value of the passed argument. If the argument is not negative, it returns the argument, and if it is negative, then the negation of the argument is returned. This will work in the same manner for the second and third iteration.

    import java.util.Arrays; public class SwapArrayNumeric   public static void main(String[] args) throws Exception   int [] a = 5,9>;  int [] b = 4,3>;  System.out.println("a[] before swapping : "+Arrays.toString(a));  System.out.println("b[] before swapping : "+Arrays.toString(b));  for(int i = 0 ; ia.length;i++)  a[i] = a[i] - b[i];  b[i] = a[i] + b[i];  a[i] = GetAbsoluteValue(a[i] - b[i]);  >  System.out.println("a[] after swapping : "+Arrays.toString(a));  System.out.println("b[] after swapping : "+Arrays.toString(b));   >  public static int GetAbsoluteValue (int a)  return Math.abs(a);  > > 
    a[] before swapping : [5, 9] b[] before swapping : [4, 3] a[] after swapping : [4, 3] b[] after swapping : [5, 9] 

    Use Bitwise Operators to Swap Two Arrays in Java

    The bitwise XOR or ^ is a binary operator that returns bit by bit XOR of an input. If the corresponding bits are different, it gives 1, else 0. For the first iteration we have firstArr[0] = firstArr[0] ^ secondArr[0] = 2 ^ 6 . The binary representation of 2 is 0010 , and 6 is 0110 .

    Bitwise XOR of 2 and 6 is

    0010 ^ 0110 = 0100 = 4 (in decimal) firstArr[0] = firstArr[0] ^ secondArr[0] = 2 ^ 6 = 4 secondArr[0] = firstArr[0] ^ secondArr[0] = 4 ^ 6 = 2 firstArr[0] = firstArr[0] ^ secondArr[0] = 4 ^ 2 = 6 

    Hence we can swap elements of the array using the bitwise operators.

    import java.util.Arrays;  public class SwapArrayBitwise   public static void main(String[] args) throws Exception   int [] firstArr = 2,4>;  int [] secondArr = 6,3>;  System.out.println("firstArr before swapping : "+Arrays.toString(firstArr));  System.out.println("secondArr before swapping : "+Arrays.toString(secondArr));  for(int i = 0 ; ifirstArr.length;i++)  firstArr[i] = firstArr[i] ^ secondArr[i];  secondArr[i] = firstArr[i] ^ secondArr[i];  firstArr[i] = firstArr[i] ^ secondArr[i];  >  System.out.println("firstArr after swapping : "+Arrays.toString(firstArr));  System.out.println("secondArr after swapping : "+Arrays.toString(secondArr));   > > 

    Источник

    How to Swap Two Elements in an ArrayList in Java

    Learn to swap two specified elements in ArrayList in Java. We will use Collections.swap() method to swap two elements within a specified arraylist at specified indices.

    The Collections.swap() method swaps the elements at the specified positions in the specified list. The index arguments must be a valid index in the list, else method will throw IndexOutOfBoundsException exception.

    public static void swap(List list, int i, int j)
    • list – The list in which to swap elements.
    • i – the index of one element to be swapped.
    • j – the index of another element to be swapped.

    Invoking this method leaves the list unchanged if the specified positions are equal.

    2. Swapping Two Elements in ArrayList

    The following Java program swaps two specified elements in a given list. In this example, we are swapping the elements at positions ‘1’ and ‘2’. The elements are these positions in the list are ‘b’ and ‘c’.

    Please note that indexes start from 0 .

    ArrayList list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e", "f")); System.out.println(list); Collections.swap(list, 1, 2); System.out.println(list);

    3. Throws IndexOutOfBoundsException

    Note that if the specified indices are out of bounds, then the method throws IndexOutOfBoundsException.

    Assertions.assertThrows(IndexOutOfBoundsException.class, () -> < Collections.swap(list, 10, 11); >);

    The above example is a java program to interchange the element value and its corresponding index values. Let me know if you have any questions.

    Источник

    Читайте также:  Javascript file input check
Оцените статью