顺序表数据结构
增
public void Insert(E data,int index ){
if (index < 0 || index > length){
throw new IllegalArgumentException("插入位置不合法,合法位置是:0 ~ " + length);
}
if (length >= capacity){
int newCapacity = capacity + (capacity >> 1);
Object[] newArray = new Object[newCapacity];
System.arraycopy(array,0,newArray,0,length);
array = newArray;
capacity = newCapacity;
}
for (int i = length;i > index;i--) {
array[i] = array[i -1];
}
array[index] = data;
length++;
}
删
@SuppressWarnings("unchecked")
public E Delete(int index) {
if (index < 0 || index > length - 1){
throw new IllegalArgumentException("删除位置不合法,合法位置是:0 ~ "+(length -1));
}
E data = (E) array[index];
for (int i = index; i < length; i++) {
array[i] = array[i+1];
}
length--;
return data;
}
查
@SuppressWarnings("unchecked")
public E Get(int index){
if (index < 0 || index > length - 1) {
throw new IllegalArgumentException("获取位置不合法,合法位置是:0 ~ "+(length -1));
}
return (E) array[index];
}
总览
package com.collection;
import java.util.Arrays;
public class ArrayList <E>{
private int length = 0;
private int capacity = 10;
private Object[] array = new Object[capacity];
public void Insert(E data,int index ){
if (index < 0 || index > length){
throw new IllegalArgumentException("插入位置不合法,合法位置是:0 ~ " + length);
}
if (length >= capacity){
int newCapacity = capacity + (capacity >> 1);
Object[] newArray = new Object[newCapacity];
System.arraycopy(array,0,newArray,0,length);
array = newArray;
capacity = newCapacity;
}
for (int i = length;i > index;i--) {
array[i] = array[i -1];
}
array[index] = data;
length++;
}
@SuppressWarnings("unchecked")
public E Delete(int index) {
if (index < 0 || index > length - 1){
throw new IllegalArgumentException("删除位置不合法,合法位置是:0 ~ "+(length -1));
}
E data = (E) array[index];
for (int i = index; i < length; i++) {
array[i] = array[i+1];
}
length--;
return data;
}
@SuppressWarnings("unchecked")
public E Get(int index){
if (index < 0 || index > length - 1) {
throw new IllegalArgumentException("获取位置不合法,合法位置是:0 ~ "+(length -1));
}
return (E) array[index];
}
@Override
public String toString() {
System.out.println(length);
StringBuilder builder = new StringBuilder();
for(int i = 0;i < length; i++) {
builder.append(array[i]).append(" ");
}
return builder.toString();
}
}
测试
package com.collection;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0;i < 5;i++){
list.Insert(i,i);
}
System.out.println(list);
list.Delete(3);
System.out.println(list);
System.out.println(list.Get(2));
}
}