动态数组
- 实现需求
- 增:(add(),addFirst(),addLast())
- 删:(remove(),removeFirst(),removeLast())
- 改:(set(),)
- 查 :(find(),contains(),isEmpty(),get(),getLast(),getFirst(),getCapacity(),getSize())
- 动态改变size:(reSize())
public class Array<E>{
private E[] data;
private int size;
public Array(int capacity){
data = (E[])new Object[capacity];
size = 0;
}
public Array(){
this(10);
}
public void add(int index,E e){
if(index < 0 || index > size){
throw new IllegalArgumentException("AddLast failed.Require index>=0 and index <= size");
}
if(size == arr.length){
resize(2*data.length)
}
for(int i = size-1; i>index;i--){
data[i+1] = data[i];
}
data[index] = e;
size++;
}
public void addFirst(E e){
add(0,e);
}
public void addLast(E e){
add(size,e);
}
}
public E remove (int index){
if(index < 0 || index > size){
throw new IllegalArgumentException("remove failed.Require index>=0 and index <= size");
}
E ret = data[index];
for(int i = index;i < size-1 ;i++){
data[i] = data[i+1];
}
size--;
data[size] = null;
if(size == data.length/4 && data.length / 2 != 0){
resize(data.length/2);
}
return ret;
}
public E removeFirst(){
remove(0);
}
public E removeLast(){
remove(size-1);
}
public E removeElement(E e){
int index = find(e);
if(index != -1){
remove(index);
}
}
public void set(int index, E e){
if(index < 0 || index > size){
throw new IllegalArgumentException("set failed.Require index>=0 and index <= size");
}
data[index] = e;
}
public int getCapacity(){
return data.length;
}
public int getSize(){
return size;
}
public int find(E e){
for(int i =0;i<size;i++){
if(e.equals(data[i])){
return i;
}
}
return -1;
}
public boolean contains(E e){
for(int i =0;i<size;i++){
if(e.equals(data[i])){
return true;
}
}
return false;
}
public boolean isEmpty(){
if(size==0){
return true;
}
return false;
}
public E get(int index){
if(index < 0 || index > size){
throw new IllegalArgumentException("get failed.Require index>=0 and index <= size");
}
return data[index];
}
public E getLast(int index){
return get(size);
}
public E getFirst(int index){
return get(0);
}
private void resize(int newCapacity){
E[] newData = (E[])new Object[newCapacity];
for(int i = 0;i<size;i++){
newData[i] = data[i];
}
data = newData;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append(String.format("Array:size = %d , capacity = %d\n", size, data.length));
res.append('[');
for (int i = 0; i < size; i++) {
res.append(data[i]);
if (i != size - 1) {
res.append(",");
}
}
res.append("]");
return res.toString();
}
}