Arrays 클래스는 배열을 조작할 수 있는 다양한 메소드를 포함하고 있으며, 배열을 리스트 형태로 다룰 수 있게 해주는 정적 팩토리 메소드도 함께 제공합니다. Java 9에서는 Arrays 클래스에 세 가지 중요한 메소드가 새롭게 추가되었습니다. 바로 Arrays.equals(), Arrays.compare(), 그리고 Arrays.mismatch()입니다.
1. Arrays.equals()
Java 9에서는 기존의 Arrays.equals() 메소드에 여러 개의 오버로드 버전이 추가되었습니다. 새로 추가된 메소드는 두 배열에 대해 fromIndex와 toIndex 매개변수를 받으며, 상대적인 인덱스 위치를 기준으로 두 배열의 동등 여부를 검사합니다.
구문
public static boolean equals(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)
위 구문에서 이 메소드는 지정된 범위 내의 두 int 배열이 서로 같으면 true를 반환합니다. char 배열에 대해서도 동일한 방식으로 작동합니다.
예제
import java.util.Arrays;
public class CompareArrayTest {
public static void arrayEqualsTest() {
int[] existRows = {0, 1, 2, 3, 4, 5};
int[] newRows = {3, 4, 5, 1, 2, 0};
System.out.println(Arrays.equals(existRows, newRows));
System.out.println(Arrays.equals(existRows, 1, 3, newRows, 3, 5));
System.out.println(Arrays.equals(existRows, 3, 5, newRows, 0, 2));
}
public static void main(String args[]) {
CompareArrayTest.arrayEqualsTest();
}
}
실행 결과
false true true
2. Arrays.compare()
Java 9에서는 Arrays.compare() 메소드에도 fromIndex/toIndex 매개변수가 추가되어, 특정 범위 내에서 상대적인 위치를 비교할 수 있게 되었습니다.
구문
public static int compare(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)
위 구문에서 이 메소드는 지정된 범위 내에서 두 int 배열을 사전순(lexicographically)으로 비교합니다.
예제
import java.util.Arrays;
public class LexicographicalArraysTest {
public static void main(String args[]) {
LexicographicalArraysTest.compareSliceArraysTest();
}
public static void compareSliceArraysTest() {
int[] tomMarks = {5, 6, 7, 8, 9, 10};
int[] daisyMarks = {5, 6, 7, 10, 9, 10};
int[] maryMarks = {5, 6, 7, 8};
System.out.println(Arrays.compare(tomMarks, 0, 3, daisyMarks, 0, 3));
System.out.println(Arrays.compare(tomMarks, 0, 4, maryMarks, 0, maryMarks.length));
System.out.println(Arrays.compare(daisyMarks, 0, 4, maryMarks, 0, maryMarks.length));
}
}
실행 결과
0 0 1
3. Arrays.mismatch()
Java 9에는 Arrays.mismatch() 메소드의 다양한 오버로드 버전이 추가되어, 두 배열 조각 사이의 첫 번째 불일치 지점의 인덱스를 찾아 반환할 수 있습니다.
구문
public static int mismatch(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)
위 구문에서 이 메소드는 지정된 범위 내에서 두 int 배열 간의 첫 번째 불일치 지점의 상대적 인덱스를 찾아 반환합니다. 불일치가 발견되지 않으면 -1을 반환하며, 반환되는 인덱스는 0(포함)부터 더 작은 범위의 길이(포함) 사이에 위치합니다.
예제
import java.util.Arrays;
public class MismatchMethodTest {
public static void main(String[] args) {
MismatchMethodTest.mismatchArraysTest();
}
public static void mismatchArraysTest() {
int[] a = {1, 2, 3, 4, 5};
int[] b = {1, 2, 3, 4, 5};
int[] c = {1, 2, 4, 4, 5, 6};
System.out.println(Arrays.mismatch(a, b));
System.out.println(Arrays.mismatch(a, c));
System.out.println(Arrays.mismatch(a, 0, 2, c, 0, 2));
System.out.println(Arrays.mismatch(a, 0, 3, c, 0, 3));
System.out.println(Arrays.mismatch(a, 2, a.length, c, 2, 5));
}
}
실행 결과
-1 2 -1 2 0