1,概念
- 數組一旦定義,其維數和維界就不再改變。
因此除了結構的初始化和銷毀之外,數組只有存取元素和修改元素值的操作。 - Array可以存放對象類型、基本數據類型的數據。
- 數組中元素在內存中按順序線性存放,通過第一個元素就能訪問隨后的元素,這樣的數組稱之為“真數組”。
1)java中定義
//一維數組的定義:在內存中開辟一塊連續的存儲空間,大小是 6 * sizeof(float)= 36*4 字節
//二維數組的定義:行連續,每行對應一個一維數組,但是每一行之間不連續。
float f[][] = new float[6][6];
float []f[] = new float[6][6];
float [][]f = new float[6][6];
float [][]f = new float[6][];//賦值:計算a的首地址,計算a[1]偏移量,找到a[1]地址,寫入數據2
a[1] = 2;
2)java中復制數組
當數據量很大時,復制的效率:
System.arraycopy
> clone()
> Arrays.copyOf
> for循環
。
以上均為淺拷貝;要實現深拷貝,需要在 clone() 方法中手動創建并初始化所有引用類型的屬性,此時要考慮避免循環引用(無限遞歸導致OOM)、破壞類的封裝性。
淺拷貝(Shallow Clone,對應深拷貝):
引用的對象只會拷貝引用地址,而不會將引用的對象重新分配內存
1>System.arraycopy
System類源碼中給出了arraycopy的方法,是native方法,也就是本地方法,肯定是最快的。
//數據量小的時候,for可能快。
public static void arraycopy(Object src, //源數組int srcPos, //源數組中的起始位置Object dest, //目標數組int destPos, //目標數據中的起始位置int length) //要復制的數組元素的數量System.arraycopy(a1, 2, a2, 3, 2);
2>clone()
java.lang.Object類的clone()方法為protected類型,不可直接調用,需要先對要克隆的類進行下列操作:
- 被克隆的類實現Cloneable接口;
- 被克隆的類覆蓋clone()方法,并且在該clone()方法中調用super.clone();
//1. 被克隆的類要實現Cloneable接口class Cat implements Cloneable {private String name;private int age;public Cat(String name, int age) {this.name = name;this.age = age;}//2. 重寫clone()方法protected Object clone() throws CloneNotSupportedException {return super.clone();}}
- 調用
//調用clone方法Cat cat2 = (Cat) cat1.clone();
3>Arrays.copyOf()、 copyOfRange()
Arrays.copyOf有十種重載方法,復制指定的數組,返回原數組的副本。
copyOf()
方法是復制數組至指定長度的(新)數組;
copyOfRange()
方法則將指定數組的指定長度復制到一個新數組中。
//newLength大于原數組,會用desc的元素填充,默認為null
T[] copyOf(T[] original, int newLength)
//endIndex大于原數組,會用desc的元素填充,默認為null
Arrays.copyOfRange(dataType[] srcArray,int startIndex,int endIndex)
4>for循環
直接for循環效率最高,其次是迭代器和 ForEach操作。
3)數組排序
//asc排序
Arrays.sort(nums)
Arrays.sort(int[] a, int fromIndex, int toIndex)//用Comparator接口實現自定義排序規則
Arrays.sort(T[] a, Comparator<? Super T> c)
//舉例:降序
Arrays.sort(arr, new Comparator<Integer>() {//重寫compare方法,最好加注解,不加也沒事public int compare(Integer a, Integer b) {//返回值>0交換return b-a;}
});
2,應用
1)哈希表
把數組的下標設為哈希表的鍵值(key),而把數組中每一個數字設為哈希表的值(value),有了這樣的哈希表,就可以O(1)實現查找。從而快速高效的解決很多問題。