容器
容器主要是指Collection所包含的实现类,常用的有List、Map以及Set三种结构。本文主要介绍了几种常见的集合实现类,对它们进行自定义实现。
- ArrayList:有序的容器列表,顺序存储着元素,可以使用下标进行索引,底层使用数组实现,使用数组拷贝实现扩容,下标索引快,插入效率低。
public class MyArrayList {
private int size;
private int DEFAULT_CAPACITY = 10;
private Object[] elements;
MyArrayList(int capacity) {
elements = new Object[capacity];
}
MyArrayList() {
elements = new Object[DEFAULT_CAPACITY];
}
/**
* 增加元素
*
* @param o
*/
public void add(Object o) {
ensureCapacity();
elements[size++] = o;
}
/**
* 指定位置增加元素
*
* @param index
* @param o
*/
public void add(int index, Object o) throws Exception {
indexCheck(index);
ensureCapacity();
System.arraycopy(elements, index, elements, index + 1, size - index);
elements[index] = o;
++size;
}
/**
* 确保容量
*/
private void ensureCapacity() {
if (size >= elements.length) {
int oldSize = elements.length;
Object[] newElements = new Object[oldSize + (oldSize >> 1)];
System.arraycopy(elements, 0, newElements, 0, size);
elements = newElements;
}
}
/**
* 按照下标进行索引
*
* @param index
* @return
*/
public Object get(int index) throws Exception {
indexCheck(index);
return elements[index];
}
/**
* 下标合法性检测
*
* @param index
* @return
* @throws Exception
*/
private boolean indexCheck(int index) throws Exception {
if (index < 0 || index >= size) {
throw new Exception("输入不合法");
}
return true;
}
/**
* 根据下标删除元素
*
* @param index
* @throws Exception
*/
public void remove(int index) throws Exception {
indexCheck(index);
System.arraycopy(elements, index + 1, elements, index, size - index);
--size;
}
/**
* 根据对象删除元素
*
* @param o
*/
public void remove(Object o) {
if (o == null) {
return;
} else {
for (int i = 0; i < size; i++) {
if (elements[i].equals(o)) {
System.arraycopy(elements, i + 1, elements, i, size - i);
--size;
return;
}
}
}
}
/**
* 返回元素个数
*
* @return
*/
public int size() {
return size;
}
/**
* 清空容器
*/
public void clear() {
for (int i = 0; i < size; i++