- 定義
數組(array)是一種線性表資料結構。用一組連續的記憶體空間,來存儲一組具有相同類型的資料。
- 如何實作随機通路
- 線性表(資料排成像一條線一樣的結構)
- 連續的記憶體空間和相同類型的資料
- 尋址公式
a[i]_address = base_address + i * date_type_size
- 容器的優勢,eg:ArrayList
将數組的操作細節封裝起來,支援動态擴容(每次擴大為原來的1.5倍)。
注:由于擴容操作設計記憶體申請和資料搬移,比較耗時。若事先能确定需要存儲的資料大小,最好在建立ArrayList的時候事先指定書大小
- 容器的劣勢:
不能存儲基本資料類型,若關注性能或希望使用基本資料類型,則選用數組
補充
位(bit) 位元組(byte)
- 各資料類型所占用的位元組數
資料類型 | 所占用位元組數 |
---|---|
byte | 1 |
short | 2 |
int | 4 |
long | 8 |
float | 4 |
double | 8 |
char | 2 |
數組常用操作
/**
* 定義data儲存資料
*/
private int data[];
/**
* 定義數組實際長度
*/
private int count;
/**
* 定義數組容量
*/
private int capacity;
public Array(int capacity) {
this.data = new int[capacity];
this.capacity = capacity;
this.count = 0;
}
/**
* 找資料
*
* @param index
* @return
*/
public int find(int index) {
if (index < 0 || index >= count) {
return -1;
}
return data[index];
}
/**
* 加資料
*
* @param index
* @param value
* @return
*/
public boolean insert(int index, int value) {
if (index < 0 || index >= count) {
return false;
}
if (count == capacity) {
return false;
}
for (int i = count - 1; i < count; i--) {
data[i + 1] = data[i];
}
data[index] = value;
++count;
return true;
}
/**
* 資料加到末尾
*
* @param value
* @return
*/
public boolean insertToTail(int value) {
if (count == capacity) {
return false;
}
data[count++] = value;
return true;
}
/**
* 删除指定位置資料
*
* @param index
* @return
*/
public boolean delete(int index) {
if (index < 0 || index >= count) {
return false;
}
for (int i = index + 1; i < count; i++) {
data[i - 1] = data[i];
}
--count;
return true;
}
/**
* 列印此數組
*/
public void printAll() {
for (int i = 0; i < count; i++) {
System.out.print(data[i] + " ");
}
System.out.println();
}
/**
* 獲得數組長度
* @return
*/
public int getCount(){
return count;
}