关于实现链表的底层原理
链表便于增删,不便于查询
package com.littlepage.linkedList; /** * 基于底层实现LinkedList * @author Littlepage * @reference bjsxt.com * */ public class LittlePagesLinkedList<E> { private Node first; private Node last; private int size; public void add(E obj) { Node node = new Node(obj); if (first == null) { node.setPrevious(null); node.setNext(null); first = node; last = node; } else { last.setNext(node); node.setPrevious(last); node.setNext(null); last = node; } size++; } public Node getFirst() { return first; } public void setFirst(Node first) { this.first = first; } public Node getLast() { return last; } public void setLast(Node last) { this.last = last; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } @SuppressWarnings("unchecked") public E getNode(int index) { if(index>=size||index<0){ throw new RuntimeException("Index out of bounds:"+index); } Node temp = first; for (int i = 0; i < index; i++) { temp = temp.getNext(); } return (E)temp.getElement(); } public void removeNode(int index) { Node temp = first; if (index < 0 || index > size - 1) { throw new RuntimeException("Index number is illegal:" + index); } if (index == 0) { first = first.getNext(); first.setPrevious(null); } else if (index == size - 1) { last = last.getPrevious(); last.setNext(null); } else { for (int i = 0; i < index - 1; i++) { temp = temp.getNext(); } temp.setNext(temp.getNext().getNext()); temp = temp.getNext().getNext(); temp.setNext(temp.getPrevious().getPrevious()); } size--; } @Override public String toString() { StringBuilder str = new StringBuilder(); str.append("["); if(first!=null){ str.append(first); Node temp=first; while((temp=temp.getNext())!=null){ str.append(","+temp); } } str.append("]"); return str.toString(); } }
package com.littlepage.linkedList; /** * 节点数据 * @author Littlepage * @reference bjsxt.com * */ public class Node { private Node previous; private Node next; private Object element; public Node(Object element) { this.element = element; } public Node getPrevious() { return previous; } public void setPrevious(Node previous) { this.previous = previous; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public Object getElement() { return element; } public void setElement(Object element) { this.element = element; } @Override public String toString() { return element.toString(); } }
package com.littlepage.linkedList; /** * 测试类 * @author Littlepage * @reference bjsxt.com * */ public class Test { public static void main(String[] args) { LittlePagesLinkedList<String> list=new LittlePagesLinkedList<>(); list.add("aa"); list.add("pp"); System.out.println(list); } }
Vector向量中大部分方法加了sychronized,保证线程安全