Pages

Monday, August 18, 2025

Swap 2 Numbers in ArrayList in Java

 import java.util.ArrayList;

import java.util.*;

public class Classroom {

    public static void swap(ArrayList<Integer> list, int idx1, int idx2) {
        int temp = list.get(idx1);
        list.set(idx1, list.get(idx2));// sets the value of idx1 to idx2
        list.set(idx2, temp);
    }

    public static void main(String[] args) {
       ArrayList<Integer> list = new ArrayList<>();
       list.add(2);
       list.add(5);
       list.add(9);
       list.add(6);
       list.add(8);

    int idx1 = 1, idx2 = 3;
        System.out.println(list);

      swap(list, idx1, idx2);
        System.out.println(list);
    }
}

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...