Arrays類別可以包含各種操作陣列的方法,並且還包含靜態工廠方法,允許將陣列視為清單。 Java 9為Arrays類別加入了三個重要的方法:Arrays.equals(),Arrays.compare()和Arrays.mismatch()。
Arrays.equal() - 在Java 9中,Arrays.equals()方法加入了幾個重載方法。新方法為提供的兩個陣列新增了fromIndex和toIndex參數。這些方法根據它們的相對索引位置檢查兩個陣列的相等性。
<strong>public static boolean equals(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)</strong>
在上述語法中,如果兩個指定的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(<strong>Arrays</strong>.<strong>equals</strong>(existRows, newRows)); System.out.println(<strong>Arrays</strong>.<strong>equals</strong>(existRows, 1, 3, newRows, 3, 5)); System.out.println(<strong>Arrays</strong>.<strong>equals</strong>(existRows, 3, 5, newRows, 0, 2)); } public static void main(String args[]) { CompareArrayTest.arrayEqualsTest(); } }
false true true
#Arrays.compare() − In Java 9, few parameters have added to the Arrays.compare() method. With fromIndex/toIndex parameters that are used for relative position comparison.
lexicographically over the specified ranges.
Example<strong>public static int compare(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)</strong>
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(<strong>Arrays.compare</strong>(tomMarks, 0, 3, daisyMarks, 0, 3)); System.out.println(<strong>Arrays.compare</strong>(tomMarks, 0, 4, maryMarks, 0, maryMarks.length)); System.out.println(<strong>Arrays.compare</strong>(daisyMarks, 0, 4, maryMarks, 0, maryMarks.length)); } }
Example
<strong>0 0 1</strong>
Output
<strong>public static int mismatch(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)</strong>
Arrays.mismatch() −
method that enables us to find and return the index of the first mismatch between two slices of arrays.Syntaximport 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(<strong>Arrays.mismatch</strong>(a, b));
System.out.println(<strong>Arrays.mismatch</strong>(a, c));
System.out.println(<strong>Arrays.mismatch</strong>(a, 0, 2, c, 0, 2));
System.out.println(<strong>Arrays.mismatc</strong><strong>h</strong>(a, 0, 3, c, 0, 3));
System.out.println(<strong>Arrays.mismatch</strong>(a, 2, a.length, c, 2, 5));
}
}
<strong>-1 2 -1 2 0</strong>
以上是在Java 9中,Arrays類別新增了哪些新方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!