arrays类可以包含各种操作数组的方法,并且还包含静态工厂方法,允许将数组视为列表。java 9向arrays类添加了三个重要的方法:arrays.equals(),arrays.compare()和arrays.mismatch()。
arrays.equal() - 在java 9中,arrays.equals()方法添加了几个重载方法。新方法为提供的两个数组添加了fromindex和toindex参数。这些方法根据它们的相对索引位置检查两个数组的相等性。
syntaxpublic 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(); }}
outputfalsetruetrue
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.
syntaxpublic static int compare(int[] a, int afromindex, int atoindex, int[] b, int bfromindex, int btoindex)
in the above syntax, the method compares two int arrays lexicographically over the specified ranges.
exampleimport 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)); }}
output001
arrays.mismatch() −in java 9, there are other overloaded methods of the arrays.mismatch() method that enables us to find and return the index of the first mismatch between two slices of arrays.
syntaxpublic static int mismatch(int[] a, int afromindex, int atoindex, int[] b, int bfromindex, int btoindex)
in the above syntax, the method finds and returns the relative index of the first mismatch between two int arrays over the specified range. it returns -1 if no mismatch has found. the index in the range of 0 (inclusive) up to the length (inclusive) of the smaller range.
exampleimport 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)); }}
output-12-120
以上就是在java 9中,arrays类新增了哪些新方法?的详细内容。