Arrays是針對數組的工具類,可以進行 排序,查找,復制填充等功能。 大大提高了開發人員的工作效率。
一 數組復制
與使用System.arraycopy進行數組復制類似的, Arrays提供了一個copyOfRange方法進行數組復制。
不同的是System.arraycopy,需要事先准備好目標數組,並分配長度。 copyOfRange 只需要源數組就就可以了,通過返回值,就能夠得到目標數組了。
除此之外,需要注意的是 copyOfRange 的 第3個參數,表示源數組的結束位置,是取不到的。
除此之外,需要注意的是 copyOfRange 的 第3個參數,表示源數組的結束位置,是取不到的。
import java.util.Arrays; public class HelloWorld { public static void main(String[] args) { int a[] = new int[] { 18, 62, 68, 82, 65, 9 }; // copyOfRange(int[] original, int from, int to) // 第一個參數表示源數組 // 第二個參數表示開始位置(取得到) // 第三個參數表示結束位置(取不到) int[] b = Arrays.copyOfRange(a, 0, 3); for (int i = 0; i < b.length; i++) { System.out.print(b[i] + " "); } } }
而用System.arraycopy進行復制的話如下
public class HelloWorld { public static void main(String[] args) { int a [] = new int[]{18,62,68,82,65,9}; int b[] = new int[3];//分配了長度是3的空間,但是沒有賦值 //通過數組賦值把,a數組的前3位賦值到b數組 //方法一: for循環 for (int i = 0; i < b.length; i++) { b[i] = a[i]; } //方法二: System.arraycopy(src, srcPos, dest, destPos, length) //src: 源數組 //srcPos: 從源數組復制數據的啟始位置 //dest: 目標數組 //destPos: 復制到目標數組的啟始位置 //length: 復制的長度 System.arraycopy(a, 0, b, 0, 3); //把內容打印出來 for (int i = 0; i < b.length; i++) { System.out.print(b[i] + " "); } } }
二 轉換為字符串
如果要打印一個數組的內容,就需要通過for循環來挨個遍歷,逐一打印但是Arrays提供了一個toString()方法,直接把一個數組,轉換為字符串,這樣方便觀察數組的內容
import java.util.Arrays; public class HelloWorld { public static void main(String[] args) { int a[] = new int[] { 18, 62, 68, 82, 65, 9 }; String content = Arrays.toString(a); System.out.println(content); } }
三排序
Arrays工具類提供了一個sort方法,只需要一行代碼即可完成排序功能。
import java.util.Arrays; public class HelloWorld { public static void main(String[] args) { int a[] = new int[] { 18, 62, 68, 82, 65, 9 }; System.out.println("排序之前 :"); System.out.println(Arrays.toString(a)); Arrays.sort(a); System.out.println("排序之后:"); System.out.println(Arrays.toString(a)); } }
四 搜索
查詢元素出現的位置
需要注意的是,使用binarySearch進行查找之前,必須使用sort進行排序
如果數組中有多個相同的元素,查找結果是不確定的
import java.util.Arrays; public class HelloWorld { public static void main(String[] args) { int a[] = new int[] { 18, 62, 68, 82, 65, 9 }; Arrays.sort(a); System.out.println(Arrays.toString(a)); //使用binarySearch之前,必須先使用sort進行排序 System.out.println("數字 62出現的位置:"+Arrays.binarySearch(a, 62)); } }
五 判斷是否相同
比較兩個數組的內容是否一樣
第二個數組的最后一個元素是8,和第一個數組不一樣,所以比較結果是false
import java.util.Arrays; public class HelloWorld { public static void main(String[] args) { int a[] = new int[] { 18, 62, 68, 82, 65, 9 }; int b[] = new int[] { 18, 62, 68, 82, 65, 8 }; System.out.println(Arrays.equals(a, b)); } }
六填充
使用同一個值,填充整個數組
import java.util.Arrays; public class HelloWorld { public static void main(String[] args) { int a[] = new int[10]; Arrays.fill(a, 5); System.out.println(Arrays.toString(a)); } }
編輯較為混亂 日后再重新整理