1.簡述
一個個獨立的數(shù)據(jù)是沒有任何意義的,可集合的可辨識的數(shù)據(jù)才有。數(shù)據(jù)的最基本的一種集合方式為數(shù)組。數(shù)組對于每一門編程語言來說都是重要的數(shù)據(jù)結(jié)構(gòu)之一,Java 語言中提供的數(shù)組是用來存儲固定大小的同類型元素。但是Java并未提供一個描述數(shù)組的類(類似于public class []<T>{} 這樣的),為了便于操作數(shù)組而提供了一個工具類java.util.Arrays;
2.數(shù)組的數(shù)據(jù)結(jié)構(gòu)
2.1一維數(shù)組

如上如圖所示,int [] a = new int[10]。這是整型的集合,可簡單依靠地址(index)去分別;按地址尋找的復雜度為O(1)按內(nèi)容尋找的復雜度為O(n);
tip:需要補充內(nèi)存的工作原理,數(shù)據(jù)結(jié)構(gòu)及算法的知識了。
2.2多維數(shù)組
實際上并不存在多維數(shù)組,只是對一維數(shù)組的擴展。所有的高緯數(shù)組都可以看成是低一緯度的數(shù)組的數(shù)組;例如二維數(shù)組就可以看作一維數(shù)組的數(shù)組,依次類推。
3.數(shù)組的特征
3.1大?。╨ength):
數(shù)組的容量,由于Java是邊解釋邊執(zhí)行,我們可以在代碼編寫時不指定數(shù)組的具體大小而是由代碼的執(zhí)行結(jié)果來來確定數(shù)組大?。–好像是不可以的,代碼編寫期間就必須制定數(shù)組的大小,這是大學時的記憶了還是譚浩強的,不知改了沒改,不能動態(tài)的搞就太蛋疼了);
3.2下標(index);
從0開始到length-1結(jié)束,用于獲取每個元素。
4.對數(shù)組的操作(排序及查找)
4.1 Arrays.asList(T... a)轉(zhuǎn)換為ArrayList:
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
4.2 Arrays.binarySearch(a, key) 二分查找:
對于已經(jīng)排序的數(shù)組(從小到大的,不能有相同的值的)搜索某個元素的下標。
原理:取范圍內(nèi)下標在中間的值進行比較,然后不斷選擇合適范圍,知道選出合適的值,個人實現(xiàn)代碼如下:
public static int binarySearch(List<Comparable> objs,Comparable comp,int startIndex,int endIndex){
Object [] objArray = objs.toArray();
if(startIndex<0){
startIndex=0;
}
if(endIndex>objArray.length-1){
endIndex = objArray.length-1;
}
while (startIndex<=endIndex) {
int midIndex = (startIndex+endIndex)/2;
Comparable target = (Comparable)objArray[midIndex];
if(comp.compareTo(target)<0){//comp<target
endIndex = midIndex-1;
continue;
}
if(comp.compareTo(target)==0){//comp == target
return midIndex;
}
if(comp.compareTo(target)>0){//comp>target
startIndex = midIndex+1;
continue;
}
}
return -1;
}
4.3 Arrays.copyOf()數(shù)組拷貝:
底層調(diào)用的是 System.arraycopy(native final方法);
注意對于基本數(shù)據(jù)類型等常量值的拷貝是可以的,但是對于一般引用類型數(shù)據(jù)的拷貝只能拷貝引用的值,如下代碼:
public class TestObject {
public static void main(String[] args) {
String [] src = new String [] {new String("0"),new String("1"),new String("2"),new String("3")};
String [] src2 = Arrays.copyOf(src, src.length);
src2[0]= new String("0000");//返回的是String Pool常量池的引用
System.out.println(src[0]);//0
Integer [] ints = new Integer[]{new Integer(0),new Integer(1),new Integer(2)};
Integer [] ints2 = Arrays.copyOf(ints, ints.length);
ints2[0] = new Integer(10);//返回的是Integer(10)Integer類常量池的引用
System.out.println(ints[0]);//0
Demo[] demo = new Demo[]{new Demo("0"),new Demo("1")};
Demo [] demo2 = Arrays.copyOf(demo, demo.length);
demo2[0].a="00000";
System.out.println(demo[0].a);//00000
int [] [] int2 = new int[2][2];
int2[0][0]=0;
int2[0][1]=1;
int2[1][0]=1;
int2[1][1]=2;
int [] [] int2s = Arrays.copyOf(int2, int2.length);
int2[0][0] = 10086;
System.out.println(int2[0][0]);//10086
}
}
class Demo{
String a;
public Demo() {
super();
}
public Demo(String a) {
super();
this.a = a;
}
}
5.數(shù)組的排序
這個打算在以后弄個專門的集合來搞這個內(nèi)容,應該是個很大的工程。