반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- CSS
- Visual Studio Code
- javascript
- IntelliJ
- string
- table
- 이클립스
- CMD
- Eclipse
- html
- ArrayList
- vscode
- list
- 자바
- 배열
- Maven
- 인텔리제이
- Array
- Button
- js
- windows
- date
- 자바스크립트
- json
- input
- 이탈리아
- 정규식
- 문자열
- 테이블
- Java
Archives
- Today
- Total
어제 오늘 내일
[Java 기초] Arrays.mismatch()로 배열의 차이점 찾기 본문
배열을 비교할 때 보통 Arrays.equals()
나 Arrays.deepEquals()
를 사용합니다.
하지만 이 메서드들은 단순히 같다/다르다(true/false)만 알려줍니다.
"어느 위치가 다른지"를 확인하려면 Arrays.mismatch()
를 쓰는 것이 훨씬 효율적입니다.
1. Arrays.mismatch()란?
- 두 배열을 앞에서부터 순차적으로 비교
- 처음으로 다른 값이 나타난 인덱스를 반환
- 두 배열이 완전히 같으면
-1
을 반환
👉 메서드 시그니처:
public static int mismatch(int[] a, int[] b)
public static <T> int mismatch(T[] a, T[] b)
2. 기본 사용 예제
import java.util.Arrays;
public class MismatchExample1 {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {1, 2, 9, 4, 5};
int index = Arrays.mismatch(arr1, arr2);
System.out.println("불일치 인덱스: " + index);
}
}
실행 결과
불일치 인덱스: 2
👉 arr1[2] = 3
vs arr2[2] = 9
가 달라서 인덱스 2
를 반환합니다.
3. 두 배열이 완전히 같을 때
import java.util.Arrays;
public class MismatchExample2 {
public static void main(String[] args) {
String[] arr1 = {"A", "B", "C"};
String[] arr2 = {"A", "B", "C"};
int index = Arrays.mismatch(arr1, arr2);
System.out.println("결과: " + index);
}
}
실행 결과
결과: -1
👉 배열이 완전히 동일하면 -1
을 반환합니다.
4. 배열 길이가 다를 때
import java.util.Arrays;
public class MismatchExample3 {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3, 4};
int index = Arrays.mismatch(arr1, arr2);
System.out.println("불일치 인덱스: " + index);
}
}
실행 결과
불일치 인덱스: 3
👉 길이가 짧은 배열의 끝을 넘어가는 부분이 불일치로 간주됩니다.
5. null 값 비교
import java.util.Arrays;
public class MismatchExample4 {
public static void main(String[] args) {
String[] arr1 = {"A", null, "C"};
String[] arr2 = {"A", "B", "C"};
int index = Arrays.mismatch(arr1, arr2);
System.out.println("불일치 인덱스: " + index);
}
}
실행 결과
불일치 인덱스: 1
👉 null
과 "B"
는 다르다고 판단합니다.
6. equals()와 mismatch() 비교
메서드 | 결과 | 용도 |
---|---|---|
Arrays.equals(a, b) |
true/false |
두 배열이 같은지만 확인 |
Arrays.mismatch(a, b) |
불일치 인덱스 or -1 |
어디가 다른지 확인 |
7. 정리
Arrays.mismatch()
→ 배열 비교 시 다른 인덱스를 빠르게 찾을 수 있음- 같으면
-1
, 다르면 최초 불일치 인덱스 반환 - 배열 길이가 다를 경우, 짧은 배열 끝 이후가 불일치로 처리됨
👉 배열이 같은지 여부뿐 아니라 어디가 다른지 확인하려면 Arrays.mismatch()
를 사용하자!
반응형
'IT > Java' 카테고리의 다른 글
[Java 기초] Collections.sort()로 리스트 정렬하기 (1) | 2025.09.01 |
---|---|
[Java 기초] Arrays.parallelSort()로 병렬 정렬하기 (1) | 2025.09.01 |
[Java 기초] Arrays.deepToString()으로 다차원 배열 출력하기 (0) | 2025.08.31 |
[Java 기초] Arrays.deepEquals()로 다차원 배열 비교하기 (0) | 2025.08.30 |
[Java 기초] Arrays.asList()로 배열을 리스트로 바꾸기 (0) | 2025.08.30 |
Comments