IT/프로그래밍

JAVA Collections swap

Collin 2019. 8. 28. 12:12
반응형

java . util. Collections

 

List 안에 있는 데이터 순서를 변경하고 싶은 경우

 

java에서 제공하는 Collections swap을 사용해서 변경할 수 있다.

 

다음은 List에 있는 문자열 객체 순서를 변경하는 경우이다.

 

A,B,C,D,E,F 문자가 있는 list에서 A와 E 순서 변경하기

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollSwapTest {

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("A");
		list.add("B");
		list.add("C");
		list.add("D");
		list.add("E");
		list.add("F");
		String targetA = "A", targetE = "E";
		int tA = -1, tE = -1;
		
		// search
		for (int i = 0; i < list.size(); i++) {
			if(targetA.equals(list.get(i))) {
				tA = i;
			}else if(targetE.equals(list.get(i))) {
				tE = i;
			}
		}
		
		printList(list);
		
		System.out.println("");
		System.out.println("swap");
		Collections.swap(list, tA, tE);
		
		printList(list);
		
	}

	private static void printList(List<String> list) {
		for (String str : list) {
			System.out.print(str + "\t");
		}
	}
}

 

swap api 

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

Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)
Parameters:
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.

Throws:
IndexOutOfBoundsException - if either i or j is out of range (i < 0 || i >= list.size() || j < 0 || j >= list.size()).

Since: 1.4

 

참조 java api docs

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

 

Collections (Java Platform SE 7 )

Rotates the elements in the specified list by the specified distance. After calling this method, the element at index i will be the element previously at index (i - distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive. (Thi

docs.oracle.com

List 순서 변경에 사용할 수 있는 Collections swap method 였습니다.

 

반응형