数组
定义:开辟连续的内存空间去存储类型相同的数据
自己动手写一个数组
代码:
public class Array<E> {
private E[] arrs;
private int size;
Array(int capcity){
arrs = (E[])new Object[capcity];
size = 0;
}
Array(){
this(10);
}
public int getSize(){
return size;
}
public E[] getArrs(){
return arrs;
}
public int getCapcity(){
return arrs.length;
}
public boolean isEmpty(){
return size == 0;
}
public void addLast(E e){
add(size,e);
}
public void addFirst(E e){
add(0,e);
}
public void add(int index , E e){
if(index < 0 || index > size){
throw new IllegalArgumentException("index not suitable");
}
if(size >= arrs.length){
resize(arrs.length * 2);
}
for(int i = size - 1; i >= index;i-- ){
arrs[i+1] = arrs[i];
}
arrs[index] = e;
size++;
}
public void set(int index , E e){
if(index < 0 || index >= size){
throw new IllegalArgumentException("index range error");
}
arrs[index] = e;
}
public E get(int index){
if(index < 0 || index >= size){
throw new IllegalArgumentException("index range error");
}
return arrs[index];
}
public boolean contains(E e){
for(int i = 0 ; i < size ; i++){
if(e.equals(arrs[i]))
return true;
}
return false;
}
public int find(E e){
for(int i = 0 ; i < size ; i++){
if(e.equals(arrs[i]))
return i;
}
return -1;
}
public E delete(int index){
if(index < 0 || index >= size){
throw new IllegalArgumentException("index illegal");
}
E res = arrs[index];
for(int i = index ; i < size - 1; i++){
arrs[i] = arrs[i+1];
}
size--;
if(size == arrs.length/4 && arrs.length != 0)
resize(arrs.length/2);
return res;
}
public E deleteFirst(){
return delete(0);
}
public E deleteLast(){
return delete(size - 1);
}
public void deleteElement(E e){
int index = find(e);
if(find(e) != (-1)){
delete(index);
}
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("Array: size = %d , capacity = %d\n",size,arrs.length));
res.append('[');
for(int i = 0 ; i < size ; i++){
res.append(arrs[i]);
if(i != size - 1){
res.append(", ");
}
}
res.append(']');
return res.toString();
}
private void resize(int newcapcity){
E[] newArr = (E[])new Object[newcapcity];
for(int i = 0 ; i < size ; i++){
newArr[i] = arrs[i];
}
arrs = newArr;
}
}