Collections 클래스

Jan 05, 2024
Collections 클래스
💡
Collections 클래스는 여러가지 유용한 알고리즘을 구현한 메서드를 제공한다.
 

1. 정렬sort

 
데이터를 어떤 기준에 의하여 순서대로 나열하는 것이다.
리스트의 원소가 String 타입이면 알파벳 순, Date 는 시간 순서로 정렬이 될 것이다.
 
public class SortTest { public static void main(String[] args) { String[] s = {"walk", "apple", "milk", "hello"}; Integer[] in = {10, 5, 71, 15, 35}; for (int i = 0; i < s.length; i++) { System.out.print(s[i] + " "); } System.out.println(); List<String> list1 = Arrays.asList(s); Collections.sort(list1); System.out.println(list1); System.out.println(); for (int i = 0; i < in.length; i++) { System.out.print(in[i] + " "); } System.out.println(); List<Integer> list2 = Arrays.asList(in); Collections.sort(list2); System.out.println(list2); } }
 
notion image
 
Arrays.asList 로 배열을 리스트로 변환했다. Collections.sort 를 호출하면 리스트를 정렬할 수 있다.
 
 

2. 섞기shuffle

 
리스트에 존재하는 정렬을 파괴시켜서 원소들의 순서를 랜덤하게 만든다.
 
public class Shuffle { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); for (int i = 0; i <= 10; i++) { list.add(i); } System.out.println(list); Collections.shuffle(list); System.out.println(list); Collections.shuffle(list); System.out.println(list); } }
 
notion image
 

3. 탐색 binarySearch

 
리스트 내부의 원하는 자료를 찾는 것이다. 리스트가 정렬되어 있지 않아면 모든 자료를 탐색하는 선형 탐색으로 할 수 밖에 없다. 하지만 리스트가 정렬이 되어있다면 , 중간 원소를 기준으로 크기를 반으로 줄일 수 있다. 이진 검색은 이전 내용에 정리했다.
 
 
public class SerchTest { public static void main(String[] args) { int num = 11; List<Integer> list = new ArrayList<>(); for (int i = 1; i < 21; i++) { list.add(i); } System.out.println(list); System.out.println("타겟값:" + num); int index = Collections.binarySearch(list, num); System.out.println("타겟의 위치: " + index); } }
 
notion image
 
Share article
RSSPowered by inblog