您的位置:首页 > 编程语言 > Java开发

12、自己实现的ArrayList

2016-09-26 19:29 316 查看
1、自己实现的ArrayList的代码如下

package com.baowei.test;

public class MyArrayList<E> {
// 表示当前的存储元素的大小
private int size = 0;
// 表示容量的大小
private int capacity = 10;
// 数值,用于保存数据
private E[] values = null;

// 无参构造函数
@SuppressWarnings("unchecked")
public MyArrayList() {
values = (E[]) new Object[capacity];
}

// 有参构造函数
@SuppressWarnings("unchecked")
public MyArrayList(int capacity) {
this.capacity = capacity;
values = (E[]) new Object[capacity];
}

public void add(E e) {
if (e == null) {
throw new RuntimeException("输入的元素为Null...");
}
if (size >= capacity) {
// 重新构造大小
enlargeCapacity();
}
// 放入元素
values[size] = e;
size++;
}

public E get(int index) {
if (index < 0 || index >= size) {
throw new RuntimeException("下标异常... ");
}
// 放入元素
return values[index];
}

public E remove(int index) {
if (index < 0 || index >= size) {
throw new RuntimeException("下标异常... ");
}

for (int i = index; i < size - 1; i++) {
values[i] = values[i + 1];
}
values[size - 1] = null;
size--;
return values[index];

}

@SuppressWarnings("unchecked")
private void enlargeCapacity() {
capacity = capacity * 2;
E[] tmpValues = (E[]) new Object[capacity];
System.arraycopy(values, 0, tmpValues, 0, size);
values = tmpValues;
}

public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(values[i]).append(",");
}
if (size > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("]");
return sb.toString();
}

public static void main(String[] args) {
MyArrayList<String> myList = new MyArrayList<String>();
myList.add("0");
myList.add("1");
myList.add("2");
myList.add("3");
myList.add("4");
myList.add("5");
myList.add("6");
myList.add("7");
myList.add("8");
myList.remove(7);
System.out.println(myList.toString());
}
}


2、参考的博客地址

http://blog.csdn.net/fenglibing/article/details/14166011
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息