package com.youjiuye.list;
/**
* @see 自定义ArrayList集合
*
* @author 丢了风筝的线
*
*/
public class UserDefinedArrayList<V> {
// 存储元素
private Object[] dataElement;
// 记录数组的下标
private int size;
// 数组的默认初始容量
private static int DEFAULT_CAPACIYT = 10;
public UserDefinedArrayList() {
dataElement = new Object[DEFAULT_CAPACIYT];
}
// 可以自定义集合的初始容量
public UserDefinedArrayList(int capacity) {
if (capacity <= 0) {
throw new RuntimeException("集合的容量不合法" + capacity);
}
dataElement = new Object[capacity];
}
// 获取元素
public V get(int index) {
IndexIllgealException(index);
return (V) dataElement[index];
}
// 设置元素
public void set(int index, V v) {
IndexIllgealException(index);
dataElement[index] = v;
}
// 添加元素
public void add(V v) {
// 当数组的下标值达到数组长度的时候,进行数组的扩容
if (size == dataElement.length) {
// 重新定义一个容量更大的数组
Object[] newdataElement = new Object[dataElement.length + (dataElement.length >> 1)];
// 将旧的数组元素拷贝到新的数组里
System.arraycopy(dataElement, 0, newdataElement, 0, dataElement.length);
// 将新的数组的地址赋值给dataElement
dataElement = newdataElement;
}
dataElement[size++] = v;
}
// 根据内容删除元素
public void remove(V element) {
for (int i = 0; i < dataElement.length; i++) {
if (dataElement[i].equals(element)) {
System.arraycopy(dataElement, i + 1, dataElement, i, dataElement.length - i - 1);
dataElement[--size] = null;
}
}
}
// 根据索引删除元素
public void remove(int index) {
if (index > 0) {
System.arraycopy(dataElement, index + 1, dataElement, index, dataElement.length - index - 1);
}
dataElement[--size] = null;
}
// 显示集合
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < size; i++) {
sb.append(dataElement[i] + ",");
}
// 将最后一个','字符替换为']'
sb.setCharAt(sb.length() - 1, ']');
return sb.toString();
}
// 获取集合的元素个数
public int Size() {
return size;
}
// 判断集合是否为空
public boolean isEmpty() {
return size == 0 ? true : false;
}
// 定义索引不合法异常
public void IndexIllgealException(int index) {
if (index < 0 || index >= size) {
throw new RuntimeException("索引不合法" + index);
}
}
}
java自定义ArrayList集合
最新推荐文章于 2024-06-12 14:33:24 发布