import java.util.Arrays;
/**
* 模拟ArrayList实现自己的顺序表
*@author 莱格
*/
public class MyArrayList {
private Object[] elementData;
private int size;//容器的大小
//返回容器的大小
public int size() {
return size;
}
//判断list是否为空
public boolean isEmpty() {
return size == 0;
}
//初始化容器的大小
public MyArrayList(int initialCapacity) {
if(initialCapacity < 0) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
elementData = new Object[initialCapacity];
}
public MyArrayList() {
this(10);
}
//添加元素
public void add(Object obj) {
//数组扩容
if (size == elementData.length) {
Object[] newArray = new Object[2*size+1];
//System.arraycopy(src, srcPos, dest, destPos, length);
for (int i = 0; i < elementData.length; i++) {
newArray[i] = elementData[i];
}
elementData = newArray;
}
elementData[size++] = obj;
}
public void add(int index,Object obj) {
rangeCheck(index);//检查索引
ensureCapacity();//数组扩容
System.arraycopy(elementData, index, elementData, index+1, size-index);
elementData[index] = obj;
size++;
}
//获得指定位置的元素
public Object get(int index) {
rangeCheck(index);
System.out.println(elementData[index]);
return elementData[index];
}
//删除指定位置的对象
public void remove(int index) {
rangeCheck(index);
// if(index < 0 || index >= size) {
// try {
// throw new Exception();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
int numMoved = size-index-1;
if(numMoved>0) {
System.arraycopy(elementData, index+1, elementData, index, numMoved);
}
elementData[--size] = null;//垃圾回收
}
//删除指定元素
public void remove(Object obj) {
for (int i = 0; i < size; i++) {
if (get(i).equals(obj)) {
remove(i);
}
}
}
public Object set(int index,Object obj) {
rangeCheck(index);
Object oldValue = elementData[index];
elementData[index] = obj;
return oldValue;
}
/**
* 数组扩容
*/
private void ensureCapacity() {
if(size == elementData.length) {
Object[] newArray = new Object[size*2+1];
System.arraycopy(elementData, 0, newArray, 0, elementData.length);
elementData = newArray;
}
}
/**
* @param index
*/
private void rangeCheck(int index) {
if (index<0 || index >= size) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//打印数组
public String toString() {
//System.out.println(elementData.toString());
return Arrays.toString(elementData);
}
//测试
public static void main(String[] args) {
MyArrayList slist = new MyArrayList(3);
slist.add(132);
slist.add(132);
slist.add("444");
slist.add(5);
slist.add("333");
slist.add("333");
slist.add("abc");
slist.add("ccc");
slist.toString();
System.out.println(slist.size);
System.out.println(slist.get(6));
slist.remove(3);
System.out.println(slist.size);
}
}
java实现ArrayList顺序表
最新推荐文章于 2023-09-14 22:12:54 发布