首页 > 编程 > Java > 正文

JAVA编程思想第4版第15章泛型的练习5

2019-11-08 02:38:06
字体:
来源:转载
供稿:网友

原来代码是:

public class LinkedStack<T> {  PRivate static class Node<U> {    U item;    Node<U> next;    Node() { item = null; next = null; }    Node(U item, Node<U> next) {      this.item = item;      this.next = next;    }    boolean end() { return item == null && next == null; }  }  private Node<T> top = new Node<T>(); // End sentinel  public void push(T item) {    top = new Node<T>(item, top);  }      public T pop() {    T result = top.item;    if(!top.end())      top = top.next;    return result;  }  public static void main(String[] args) {    LinkedStack<String> lss = new LinkedStack<String>();    for(String s : "Phasers on stun!".split(" "))      lss.push(s);    String s;    while((s = lss.pop()) != null)      System.out.println(s);  }}去掉Node类上的类型参数,内部类可以访问其外部类的类型参数,即原来是嵌套(静态)内部类,现在要修改为成员内部类即可,具体如下:
public class LinkedStack<T> {    private  class Node{        T item;        Node next;        Node(){            item = null;            next = null;        }        Node(T item,  Node next){            this.item = item;            this.next = next;        }        boolean end(){            return (item == null) && (next==null);        }    }    private Node top = new Node();    public void push(T item){        top = new Node(item, top);    }    public T top(){        T result = top.item;        if(!top.end()){            top = top.next;        }        return result;    }    public static void main(String[] args) {        LinkedStack<String> lss = new LinkedStack<String>();        for(String s:"Phasers on stun!".split(" ")){            lss.push(s);        }        String s;        while ((s=lss.top())!= null){            System.out.println(s);        }    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表