Arrays Class Enhancements ใน Java 9
Java 9 เพิ่มเมธอดสำคัญ 3 เมธอดให้ Arrays class: equals(), compare(), mismatch() รองรับ range comparison (fromIndex, toIndex)
1. Arrays.equals() - เปรียบเทียบช่วง (Range Equality)
Syntax
public static boolean equals(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)
ตัวอย่าง
int[] existRows = {0, 1, 2, 3, 4, 5};
int[] newRows = {3, 4, 5, 1, 2, 0};
Arrays.equals(existRows, newRows); // false
Arrays.equals(existRows, 1, 3, newRows, 3, 5); // true (1,2 vs 1,2)
Arrays.equals(existRows, 3, 5, newRows, 0, 2); // true (3,4 vs 3,4)
Output
false true true
2. Arrays.compare() - เปรียบเทียบ Lexicographically ด้วย Range
Syntax
public static int compare(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)
ตัวอย่าง
int[] tomMarks = {5, 6, 7, 8, 9, 10};
int[] daisyMarks = {5, 6, 7, 10, 9, 10};
int[] maryMarks = {5, 6, 7, 8};
Arrays.compare(tomMarks, 0, 3, daisyMarks, 0, 3); // 0 (equal)
Arrays.compare(tomMarks, 0, 4, maryMarks, 0, 4); // 0 (equal)
Arrays.compare(daisyMarks, 0, 4, maryMarks, 0, 4); // 1 (daisy > mary)
Output
0 0 1
3. Arrays.mismatch() - หา Index แรกที่ต่างกันใน Range
Syntax
public static int mismatch(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)
ตัวอย่าง
int[] a = {1, 2, 3, 4, 5};
int[] b = {1, 2, 3, 4, 5};
int[] c = {1, 2, 4, 4, 5, 6};
Arrays.mismatch(a, b); // -1 (same)
Arrays.mismatch(a, c); // 2 (index 2: 3 vs 4)
Arrays.mismatch(a, 0, 2, c, 0, 2); // -1 (range 0-2 same)
Arrays.mismatch(a, 0, 3, c, 0, 3); // 2 (range 0-3 differ at 2)
Arrays.mismatch(a, 2, 5, c, 2, 5); // 0 (relative index in range)
Output
-1 2 -1 2 0
สรุป
เมธอดใหม่ทั้ง 3 รองรับ range comparison ทำให้เปรียบเทียบ array สลายนี้ได้แม่นยำและยืดหยุ่นกว่าเดิม