|
http://hi.baidu.com/zk_ajax/blog/item/8efd7fc77b5a5dddd10060f8.html
感觉毕业以来自己都比较浮躁,以前想研究Jive系统的,但后来在网上看到有人说过时了,近来没事,看了部分代码,感觉写的相当漂亮,先撇开设计模式不说,我今天分析一下lastComma它里面的链表的实现:
public class LinkedListNode {public LinkedListNode previous;public LinkedListNode next;public Object object;public LinkedListNode(Object object, LinkedListNode previous,LinkedListNode next) {this.previous = previous;this.next = next;this.object = object;}public void remove() {previous.next = next;next.previous = previous;}@Overridepublic String toString() {return object.toString();}public LinkedListNode getPrevious() {return previous;}public void setPrevious(LinkedListNode previous) {this.previous = previous;}public LinkedListNode getNext() {return next;}public void setNext(LinkedListNode next) {this.next = next;}public Object getObject() {return object;}public void setObject(Object object) {this.object = object;}}
链表类:
public class LinkedList {private LinkedListNode head = new LinkedListNode("head", null, null);public LinkedList() {head.previous = head.next = head;}public LinkedListNode getFirst() {LinkedListNode node = head.next;if (node == head) {return null;}return node;}public LinkedListNode getLast() {LinkedListNode node = head.previous;if (node == head) {return null;}return node;}public void addFirst(LinkedListNode node) {node.next = head.next;node.previous = head;node.next.previous = node;node.previous.next = node;}public void addFirst(Object object) {LinkedListNode node = new LinkedListNode(object, head, head.next);node.next.previous = node;node.previous.next = node;}public void addLast(Object object) {LinkedListNode node = new LinkedListNode(object, head.previous, head);node.previous.next = node;node.next.previous = node;}public void clear() {LinkedListNode node = getLast(); //把head也释放一下,我感觉这个比较高明,我实现的时候肯定head就忘记 //释放了,造成内存泄露。while (node != null) {node.remove();node = getLast();}head = head.next = head.previous;}public void add(Object object){addLast(object);} public String toString() {LinkedListNode node = head.next;StringBuffer buffer = new StringBuffer();buffer.append("["); // 把head不打印出来while (node != head) {buffer.append(node.toString() + ",");node = node.next;} // 这个是我自己加的,仿照List的toString,两边加上[],并且删除 // 最后一个,int lastComma = -1;if((lastComma = buffer.lastIndexOf(",")) != -1){buffer.deleteCharAt(lastComma);}buffer.append("]");return buffer.toString();}} |
|