这是我用java实现的数据结构中的顺序表,以下是我的代码
package com.husiwang.SqList;
/**
* Created by SiwangHu on 2015/2/1.
*/
public class ArrayList {
private Object[] Data; //数据缓冲区
private int Capacity; //数据容量
private int Current; //末元素的下一个位置
//无参构造函数
public ArrayList(){
Capacity=20;
Current=0;
Data=new Object[Capacity];
}
//指定容量大小的构造函数
public ArrayList(int capacity){
if(capacity>0) {
Capacity = capacity;
Current = 0;
Data = new Object[Capacity];
}
else{
throw new RuntimeException("初始化大小必须大于0");
}
}
//返回当前容量
public int getCapacity() {
return Capacity;
}
//返回当前下标位置
public int getCurrent() {
return Current;
}
//返回长度
public int Length(){
return Current;
}
//判断是否为空
public boolean IsEmpty(){
if(Current==0)
return true;
else
return false;
}
//扩充容量
public void IncreaseCapacity()
{
Object[] temp=new Object[Capacity];
for(int i=0;i
temp[i] = Data[i];
}
Capacity=Capacity*2;
Data=new Object[Capacity];
for(int i=0;i
Data[i]=temp[i];
}
}
//扩充容量
public void IncreaseCapacity(int multiple)
{
Object[] temp=new Object[Capacity];
for(int i=0;i
temp[i] = Data[i];
}
Capacity=Capacity*multiple;
Data=new Object[Capacity];
for(int i=0;i
Data[i]=temp[i];
}
}
//向末尾添加元素
public void Insert(Object data){
if(Current
Data[Current] = data;
Current++;
}else{
IncreaseCapacity();
Data[Current]=data;
Current++;
}
}
//在指定位置插入元素
public void Insert(int current,Object data){
if(current>Current)
throw new RuntimeException("下标过界");
else {
if(Current==Capacity)
IncreaseCapacity();
else {
for (int i = Current; i > current; i--) {
Data[i] = Data[i - 1];
}
Data[current] = data;
Current++;
}
}
}
//移除最后一个元素
public void Remove(){
if(!IsEmpty())
Current--;
else
return;
}
//移除指定位置的元素
public void Remove(int current) {
if (!IsEmpty()) {
if (current
for (int i = current; i
Data[i] = Data[i + 1];
}
Current--;
} else {
throw new RuntimeException("下标过界");
}
}
else {
return;
}
}
//查找是否存在指定的元素
public boolean Find(Object data){
for(int i=0;i
if(Data[i]==data)
return true;
}
return false;
}
//获取指定下标的元素
public Object Get(int current){
if(current
return Data[current];
else
throw new RuntimeException("下标过界");
}
//修改指定下标的元素
public void Set(int current,Object data){
if(current
Data[current]=data;
}
else{
throw new RuntimeException("下标过界");
}
}
@Override
public String toString() {
String temp="";
for(int i=0;i
temp+=String.valueOf(Data[i])+" ";
}
return "ArrayList{" +
"Data=" + temp +
", Capacity=" + Capacity +
", Current=" + Current +
'}';
}
}