1. 自定義數組的二次封裝
主要想實現的功能:
- boolean isEmpty();
- E get(int index) // 查找索引對應的元素e
- E set( int index, E e) //修改index索引位置的元素e
- boolean contains(E e) //查找數組中是否有元素e
- int find(E e) //查找元素e對應的索引位置,如果不存在元素返回-1
- add( E e)系列
- remove(E e)系列
實現代碼如下:
public class Array<E> {
//在自己封裝的類中,成員變量最好都是私有的,其它人只能通過方法來獲取成員信息。
private E[] data;
private int size;
/**
*傳入數組的容量構造Array
* @param capacity
*/
public Array(int capacity){
data = (E[])new Object[capacity];
size = 0;
}
//無參構造函數,默認初始容量是10
public Array(){
this(10);//邏輯上聲明一個初始值
}
//1.獲取數組的元素個數或容量
public int getSize(){ return size; }
public int getCapacity(){ return data.length;}
//2.數組判空
public boolean isEmpty(){return size==0;}
//3.獲取某索引對應元素
public E get(int index) {
return data[index];
}
//4.獲取元素對應的索引位置
public int find(E e){
for(int i=0; i<size; i++){
if(data[i].equals(e)) return i;
}
return -1;
}
//5.判斷元素存在
public boolean contains(E e){
for(int i=0; i<size; i++) {
if (data[i].equals(e)) return true;
}
return false;
}
//6.添加元素系列
public void add(int index, E e){
if(size == data.length)
throw new IllegalArgumentException("Add failed.Array is full.");
if(index < 0 || index > size)
throw new IllegalArgumentException("Add failed. Require index >=0");
for(int i = size-1; i>=index; i--) {data[i+1] = data[i];}
data[index] = e;
size++;
}
public void addLast(E e){
add(size, e);
}
public void addFirst(E e){
add(0,e);
}
//7.刪除元素系列
public E remove(int index){
if(index<0 || index>size)
throw new IllegalArgumentException("Remove failed. Index is Illegal");
E ret = data[index];
for(int i=index+1; i<size; i++){ data[i-1] = data[i]; }
size--;
return ret;
}
public E removeFirst(){
return remove(0);
}
public E removeLast(){
return remove(size-1);
}
//注意:已經制定了要刪除的元素,就不需要索引了
public void removeElement(E e){
int index = find(e);
if(index!=-1) remove(index);
}
}
2. 數組功能
1.找出數組中的最大值
double max = arr[0];
for(int i; i<arr.length; i++){
if(arr[i]>max) max = arr[i];
}
2.複製數組
int N = arr.length
double[] b = new double[N];
for(int i=0; i<N; i++) {
for(int i=0; i<N; i++) b[i] = a[i];
}
3.顛倒數組元素的順序
int N = arr.length
for(int i=0; i<N; i++) {
for(int i=0; i<N/2; i++)
int tmp = arr[N-1-i];
arr[N-1-i] = arr[i];
arr[i] = tmp;
}
3. 使用泛型
-
讓自己的數據結構可以“任意地”放數據類型(不可以放基本數據類型,只能是類對象)
-
每個基本數據類型都有一個對應的包裝類,這樣就方便使用泛型了
boolean, byte, char, short, int, long, float, double
Boolean, Byte, Char, Short, Int, Long, Float, Double