Java 변수 간 값 Swap 방식 5가지

  1. Swapping primitives - swap 메서드에서 b, a를 대입한 b를 파라미터로 넘겨주고 받은 리턴값 b를 a에 대입한다

class Main {
	public static int swap(int... args) { return args[0]; }

	public static void main(String[] args) {
		int a = 5;
		int b = 10;
		a = swap(b, b = a); // a = 10, b = 5		
	}
}
  1. Swapping array elements - 교환할 값이 배열의 요소이면 배열인덱스로 접근해서 교환하는 메서드를 짤 수 있다.

class Main {
    public static void swap(int[] arr int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 
    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 4, 5 };
        swap(arr, 2, 3);
    }
}
  1. Swapping Objects, AtomicInteger - 객체로 wrapping해서 내부 값을 교환하는 방식

  1. java.util.concurrent.atomic.AtomicInteger로 wrapping할 수도 있다.

  1. Collections.swap(list, i, j);

  • public static void swap(List<?> list, int i, int j)

Last updated