自己实现ArrayList与LinkedList类

时间:2022-02-03 17:33:14

ArrayList与LinkedList的底层实现

  • ArrayList内部由数组实现,LinkedList内部由链表实现。

  • 自己动手实现ArrayList与LinkedList中一些常用方法

    • ArrayList的实现

import java.util.Date;

public class SxArrayList {

	private Object[] elementDate;

	private int size;

	public SxArrayList() {
this(10);
} public boolean isEmpty() {
return size == 0;
} public SxArrayList(int initalCapacity) {
if(initalCapacity < 0) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
elementDate = new Object[initalCapacity];
} public int size() {
return size;
}
public void add(Object obj) {
//数组扩容
if(size+1 > elementDate.length) {
//申请新数组
Object[] newArray = new Object[size*2];
//将老数组内容拷贝
System.arraycopy(elementDate, 0, newArray, 0, elementDate.length);
elementDate = newArray;
}
elementDate[size++] = obj;
} public Object get(int index) {
if(index < 0 || index >= size) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return elementDate[index];
} public void remove(int index) {
//删除指定位置的对象
int numMoved = size - index -1;
if(numMoved > 0) {
System.arraycopy(elementDate, index+1, elementDate, index, numMoved);
}
elementDate[--size] = null;
} public static void main(String[] args) {
SxArrayList list = new SxArrayList(3);
list.add("edasd");
list.add(232);
list.add(new Date());
list.add(456);
System.out.println(list.size());
System.out.println(list.get(3));
System.out.println(list.get(4)); //下标越界,抛出异常 }
}

注意:在查找元素时,ArrayList内部通过equals方法实现。

LinkedList的实现

由于LinkedList由链表实现,链表由节点构成,所以把节点单独定义成一个类

//用来表示一个节点
public class Node{
Node previous;
Object obj;
Node next; public Node() { } public Node(Node previous, Object obj, Node next) {
super();
this.previous = previous;
this.obj = obj;
this.next = next;
} public Node getPrevious() {
return previous;
} public void setPrevious(Node previous) {
this.previous = previous;
} public Object getObj() {
return obj;
} public void setObj(Object obj) {
this.obj = obj;
} public Node getNext() {
return next;
} public void setNext(Node next) {
this.next = next;
} }

通过节点类构造链表,并实现常用方法


/**
* 实现LinkedList
*
*/
public class SxLinkedList {
private Node first;
private Node last; private int size; public void add(Object obj) {
Node n = new Node();
if(first == null) {
//Node n = new Node();
n.setPrevious(null);
n.setObj(obj);
n.setNext(null); first = n;
last = n;
}else {
//直接加到last后面
n.setPrevious(last);
n.setObj(obj);
n.setNext(null); last.setNext(n); last = n;
}
size ++;
} public int size() {
return size;
} public Object get(int index) { Node temp = first;
for(int i = 0;i < index; i++) {
temp = temp.next;
}
return temp.obj; } public static void main(String[] args) {
SxLinkedList list = new SxLinkedList();
list.add("aaa");
list.add(123);
System.out.println(list.size()); }
}