以前学习过链表的时候由于类型的接收不同,每次要重写链表
下面修改可用链表
class Link{ private class Node{ private Object data ; private Node next ; public Node (Object data){ this.data = data ; } public void add(Node newNode){ if(this.next == null) this.next = newNode; else{ this.next.add(newNode) ; } } public void print(){ System.out.println(this.data) ; if(this.next == null) return ; else { this.next.print() ; } } public boolean containsNode(Object data){ if(data.equals(this.data)) return true; else { if(this.next != null) return this.next.containsNode(data); else return false ; } } public Object getNode(int index){ if(Link.this.foot ++ == index){ return this.data ; } else { return this.next.getNode(index) ; } } public void setNode(int index ,Object data){ if(Link.this.foot ++ == index){ this.data = data ; } else{ this.next.setNode(index,data) ; } } public void removeNode(Node previous ,Object data) { if(data.equals(this.data)){ previous.next = this.next ; } else { this.next.removeNode(this,data) ; } } public void toArrayNode(){ Link.this.retArray[Link.this.foot ++ ] = this.data ; if(this.next != null) this.next.toArrayNode() ; } } private Node root ; private int count = 0 ; private int foot = 0 ; private Object [] retArray ; public void add(Object data){ if(data == null) return ; Node newNode = new Node(data) ; if (root == null) root = newNode; else { this.root.add(newNode) ; } this.count ++ ; } public void print(){ this.foot = 0 ; if(root == null) return ; else{ root.print() ; } } public int size() { return this.count ; } public boolean isEmpty(){ return this.count == 0 ; } public boolean contains(Object data) { if(this.root == null || data == null) return false ; else { return this.root.containsNode(data) ; } } public Object get(int index){ if(index > this.count) return null ; else{ return this.root.getNode(index) ; } } public void set(int index , Object data) { if(index > this.count) return ; else{ this.foot = 0 ; this.root.setNode(index,data) ; } } public void remove(Object data){ if(this.contains(data)){ if(data.equals(this.root.data)) this.root = this.root.next ; else{ this.root.next.removeNode(root,data) ; } } } public Object [] toArray(){ if(this.root == null){ return null ; } else { this.foot = 0 ; this.retArray = new Object[this.count] ; this.root.toArrayNode() ; return this.retArray ; } } } public class Link1{ public static void main(String args[]){ Link all = new Link() ; all.add("A") ; //String转为Object all.add("B") ; all.add("C") ; all.remove("A") ;//String已经覆写了equals()方法 Object [] data = all.toArray(); for(int x = 0 ; x < data.length ; x ++){ String str = (String)data[x] ; //每一个对象向下转型 Object变为String System.out.println(str) ; } } }
总结:
Object类对象可以接受一切数据类型,解决了数据统一问题