프로그래밍/JAVA

[JAVA] Arrays.sort 정렬

하와이블루 2024. 8. 30. 22:59
728x90

 

 

자바에서 배열을 오름/내림차순 정렬하기 위한 알고리즘을 메소드로 제공한다.

 

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html

 

Arrays (Java SE 11 & JDK 11 )

Compares two int arrays lexicographically over the specified ranges. If the two arrays, over the specified ranges, share a common prefix then the lexicographic comparison is the result of comparing two elements, as if by Integer.compare(int, int), at a rel

docs.oracle.com

 

Docs를 확인해보면 sort 메소드는 int, double, float, long 과 같은 기본형 타입의 배열 뿐만 아니라 참조형 타입의 배열도 지원하고 있다.

 

import java.util.Arrays;
import java.util.Collections;

public class Test{

    public static void main(String[] args) {
        Integer[] intArr = {5,4,3,2,1};

        Arrays.sort(intArr); // 오름차순 정렬
        for (int i : intArr){
            System.out.print(i + " ");
        }

        System.out.println();

        Arrays.sort(intArr, Collections.reverseOrder()); // 내림차순 정렬
        for (int i : intArr){
            System.out.print(i + " ");
        }
    }
}


// 결과
1 2 3 4 5 
5 4 3 2 1

 

여기서 Integer형 대신 int형을 사용하면 에러가 발생한다.

reason: no instance(s) of type variable(s) T exist so that int[] conforms to T[]

 

그 이유는 int[] 타입은 제네릭인 T[]타입으로 변환 할 수 없기 때문이다.

 

 

 

 

참고.

int[]을 Integer[]으로 변환하는 방법은 다음과 같다.

Integer[] numAyy2 = Arrays.stream(numArr1).boxed().toArray(Integer[]::new);

 

https://bluechanyeong.tistory.com/entry/int-to-Integer-Integer-to-int

 

 

 

728x90