世道变了,面试初级Java开发会问到Arrays!!!你不会还不知道吧!
一、基本定義
Arrays類,全路徑java.util.Arrays,主要功能為操作數組,Arrays類的所有方法均為靜態方法,所以
調用方式全部為Arrays.方法名
二、常用方法
1. <T> List<T> asList(T... a)可以將數組轉化為相應的list集合,但是也只能轉化為list,asList方法內部構建了一個內部靜態類ArrayList,
這個ArrayList也繼承自AbstractList,但并不是我們集合中常用的ArrayList,這兩者是有區別的,需注意,
內部靜態類AbstractList也實現了contains,forEach,replaceAll,sort,toArray等方法,但add,remove等方法則沒有
Integer[] array = new Integer[]{1,2,3}; int[] array2 = new int[]{1,2,3}; List<Integer> list1 = Arrays.asList(1,2,3); List<Integer> list2 = Arrays.asList(array); List<int[]> list3 = Arrays.asList(array2);fill方法有多個重載,分別對應幾種基本數據類型以及引用類型(Object),
fill(int[] a, int val)會將整個數組的值全部覆蓋為val
fill(int[] a, int fromIndex, int toIndex, int val)則提供了可選的開頭和結尾(不包括)
源碼如下:
我們可以看到可選開頭結尾的重載方法會先做數組越界的校驗,防止非法輸入
/** * Assigns the specified double value to each element of the specified* range of the specified array of doubles. The range to be filled* extends from index <tt>fromIndex</tt>, inclusive, to index* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the* range to be filled is empty.)** @param a the array to be filled* @param fromIndex the index of the first element (inclusive) to be* filled with the specified value* @param toIndex the index of the last element (exclusive) to be* filled with the specified value* @param val the value to be stored in all elements of the array* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or* <tt>toIndex > a.length</tt> */public static void fill(double[] a, int fromIndex, int toIndex,double val){rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++)a[i] = val;} /** * Assigns the specified float value to each element of the specified array* of floats.** @param a the array to be filled* @param val the value to be stored in all elements of the array */public static void fill(float[] a, float val) {for (int i = 0, len = a.length; i < len; i++)a[i] = val;} /** * Checks that {@code fromIndex} and {@code toIndex} are in* the range and throws an exception if they aren't. */private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");} if (fromIndex < 0) { throw new ArrayIndexOutOfBoundsException(fromIndex);} if (toIndex > arrayLength) {throw new ArrayIndexOutOfBoundsException(toIndex);}}存在多個重載方式,此處以int舉例
從樣例中我i們看到,copyOf復制后的數組長度可以大于復制前的數組,根據源碼發現,超出的元素被填充為0,引用類型則填充為null
int[] array = new int[]{1,2,3}; int[] array2 = Arrays.copyOf(array, 4); public static int[] copyOf( int[] original, int newLength) { int[] copy = new int[newLength];System.arraycopy(original, 0, copy, 0,Math.min(original.length, newLength));return copy;}對于copyOfRange,可以選擇復制的開頭和結尾(不包括),且結尾下標可以大于原數組長度,超出的下標會被填充
int[] array = new int[]{1,2,3,4,5,6,7,8,9}; int[] array2 = Arrays.copyOfRange(array, 3, 6); int[] array3 = Arrays.copyOfRange(array, 3, 10); /** * Copies the specified range of the specified array into a new array.* The initial index of the range (<tt>from</tt>) must lie between zero* and <tt>original.length</tt>, inclusive. The value at* <tt>original[from]</tt> is placed into the initial element of the copy* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).* Values from subsequent elements in the original array are placed into* subsequent elements in the copy. The final index of the range* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,* may be greater than <tt>original.length</tt>, in which case* <tt>0</tt> is placed in all elements of the copy whose index is* greater than or equal to <tt>original.length - from</tt>. The length* of the returned array will be <tt>to - from</tt>.** @param original the array from which a range is to be copied* @param from the initial index of the range to be copied, inclusive* @param to the final index of the range to be copied, exclusive.* (This index may lie outside the array.)* @return a new array containing the specified range from the original array,* truncated or padded with zeros to obtain the required length* @throws ArrayIndexOutOfBoundsException if {@code from < 0}* or {@code from > original.length}* @throws IllegalArgumentException if <tt>from > to</tt>* @throws NullPointerException if <tt>original</tt> is null* @since 1.6 */public static int[] copyOfRange(int[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); int[] copy = new int[newLength];System.arraycopy(original, from, copy, 0,Math.min(original.length - from, newLength)); return copy;}4.boolean equals(int[] a, int[] a2)、boolean equals(Object[] a, Object[] a2)
比較2個數組是否相等,基本類型的元素會依次進行==判斷,引用類型則會在判空后使用equal
public static boolean equals(int[] a, int[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true;} public static boolean equals(Object[] a, Object[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) {Object o1 = a[i];Object o2 = a2[i]; if (!(o1==null ? o2==null : o1.equals(o2))) return false;} return true;}5.String toString(int[] a)
假設我們想輸出一個數組的全部元素,一種方法是利用循環遍歷所有元素后挨個輸出
但Arrays提供了一個方案可以直接調用,toString內部實現其實也是通過遍歷來實現,
利用可變字符串StringBuilder來構建
public static String toString(int[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]";StringBuilder b = new StringBuilder();b.append('['); for (int i = 0; ; i++) {b.append(a[i]); if (i == iMax) return b.append(']').toString();b.append(", ");}}Arrays內置的二分查找方法,使用條件為參數數組a是有序的,如無序
會導致返回結果錯誤
1 public static int binarySearch(int[] a, int fromIndex, int toIndex, 2 int key) { 3 rangeCheck(a.length, fromIndex, toIndex);4 return binarySearch0(a, fromIndex, toIndex, key); 5 }6 7 // Like public version, but without range checks.8 private static int binarySearch0(int[] a, int fromIndex, int toIndex, 9 int key) { 10 int low = fromIndex; 11 int high = toIndex - 1; 12 13 while (low <= high) {14 int mid = (low + high) >>> 1; 15 int midVal = a[mid]; 16 17 if (midVal < key) 18 low = mid + 1; 19 else if (midVal > key) 20 high = mid - 1; 21 else 22 return mid; // key found 23 } 24 return -(low + 1); // key not found. 25 }最后,祝大家早日學有所成,拿到滿意offer
總結
以上是生活随笔為你收集整理的世道变了,面试初级Java开发会问到Arrays!!!你不会还不知道吧!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蔚来高管暗示新车超越宝马3系!网友:ET
- 下一篇: 转手价格飙到万元 央视评玲娜贝儿玩偶被炒