模拟实现ArrayList容器的底层实现
程序员文章站
2022-04-18 18:37:03
...
public class Human {
private String name;
public Human(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.util.ArrayList;
/**
* 模拟实现JDK中提供的ArrayList类
*
* @author 86176
*
*/
public class MyArrayList {
/**
* The value is used for character storage.
*/
private Object[] value;
/**
* The size is the number of characters used.
*/
private int size;
//创建一个容器
public MyArrayList() {
// value =new Object[16];
this(10);
}
public MyArrayList(int size) {
if (size < 0) {
try {
throw new Exception(); // 手动抛出一个异常
} catch (Exception e) {
e.printStackTrace();
}
}
value = new Object[size];
}
// 容器中方法
public int size() {
return size();
}
public boolean isEmpty() {
return size == 0;
}
public int indexOf(Object obj) {
if (obj == null) {
return -1;
} else {
for (int i = 0; i < value.length; i++) {
if (obj == value[i]) {
return i;
}
}
return -1;
}
}
public int lastindexOf(Object obj) {
if (obj == null) {
return -1;
} else {
for (int i = value.length-1; i >=0; i--) {
if (obj == value[i]) {
return i;
}
}
return -1;
}
}
public Object set(int index, Object object) {
rangeCheck(index);
Object old=value[index];
value[index] = object;
return old;
}
public void rangeCheck(int index) {
if (index < 0 || index > size - 1) { // [0,size-1]
try {
throw new Exception(); // 手动抛出一个异常
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void add(Object obj) {
value[size] = obj;
size++;
if (size >= value.length) {
// 装不下,扩容吧
int newCapacity = value.length * 2;
Object[] newList = new Object[newCapacity];
// System.arraycopy(src, srcPos, dest, destPos, length);
for (int i = 0; i < value.length; i++) {
newList[i] = value[i];
}
value = newList;
}
}
public Object get(int index) {
rangeCheck(index);
return value[index];
}
public static void main(String[] args) {
MyArrayList list = new MyArrayList(2);
list.add("aaa");
list.add(new Human("张三"));
list.add("bbb");
list.add("bbb");
list.add("bbb");
list.add("bbb");
ArrayList list2;
Human h = (Human) list.get(1);// 强制转换
System.out.println(h.getName());
System.out.println(list.get(2));
System.out.println(list.get(0));
// System.out.println(list.get(3));//超出范围,抛出异常
System.out.println(list.size);
}
}
输出:
张三
bbb
aaa
6
上一篇: ArrayList 底层实现的模拟实例
下一篇: ArrayList类的实现