jdk中的ArrayList就是一个不断扩大的数组,扩大后数组长度为(前数组长度*3)/2+1
package com.cbxjj.iterator;
import java.util.Arrays;
public class ArrayList {
private int index = 0;// list长度
static Object[] objects = new Object[10];
public int size() {
return index;
}
public void add(Object o) {
index++;
int oldNum = objects.length;
if (index > oldNum) {
int newNum = (oldNum * 3) / 2 + 1;
if (newNum < index) {
newNum = index;
}
objects = Arrays.copyOf(objects, newNum);
}
objects[index - 1] = o;
}
@Override
public String toString() {
return Arrays.toString(Arrays.copyOf(objects, index));
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
for (int i = 0; i < 50; i++) {
list.add(i);
}
System.out.println(list);
}
}
LinkedList
package com.cbxjj.iterator;
public class LinkList {
private Node head = null;// 节点首部
private Node tail = null;// 节点尾部
private int size = 0;
public int size() {
return size;
}
/***************************************************************************
* 添加节点
*
* @param o
*/
public void add(Object o) {
Node n = new Node(o, null);
if (head == null) {
head = n;
tail = n;
} else {
tail.setNext(n);
tail = n;
}
size++;
}
/**
* 删除节点
*
* @param index
*/
public void remove(int index) {
if (index == 0) {
head = get(index + 1);
} else if (index == size) {
tail = get(index - 1);
} else {
Node lastNode = get(index - 1);// 上一个节点
Node nextNode = get(index + 1);// 下一个节点
lastNode.setNext(nextNode);
}
size--;
}
/**
* 按照索引来取节点
*
* @param index
* @return
*/
public Node get(int index) {
if (index == 0)
return head;
Node node = head;
for (int i = 0; i < index; i++) {
node = node.getNext();
}
return node;
}
@Override
public String toString() {
StringBuffer res = new StringBuffer("");
if (size == 0) {
res.append("[").append("]");
}
if (size == 1) {
res.append("[").append(get(0).getData()).append("]");
} else {
for (int i = 0; i < size; i++) {
if (i == 0) {
res.append("[");
res.append(get(i).getData());
res.append(",");
} else if (i == size - 1) {
res.append(get(i).getData());
res.append("]");
} else {
res.append(" " + get(i).getData());
res.append(",");
}
}
}
return res.toString();
}
public static void main(String[] args) {
LinkList list = new LinkList();
for (int i = 0; i < 1; i++) {
list.add(i);
}
System.out.println(list);
list.remove(0);
System.out.println(list);
}
public class Node {
private Object data;// 节点数据
private Node next;// 下一个节点
public Node(Object data, Node next) {
super();
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}