集册 Java实例教程 使用泛型参数创建泛型堆栈类

使用泛型参数创建泛型堆栈类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

561
使用泛型参数创建泛型堆栈类

import java.util.LinkedList;


class GenStack<E> {

  private LinkedList<E> list = new LinkedList<E>();/** 时 代 J a v a 公 众 号 提供 **/


  public void push(E item) {

    list.addFirst(item);

  }


  public E pop() {

    return list.poll();

  }


  public E peek() {

    return list.peek();

  }


  public boolean hasItems() {

    return !list.isEmpty();

  }/*from N o  w  J a v a . c o m - 时  代  Java*/


  public int size() {

    return list.size();

  }


}


public class Main {

  public static void main(String[] args) {

    GenStack<String> gs = new GenStack<String>();


    System.out.println("Pushing four items onto the stack.");

    gs.push("One");

    gs.push("Two");

    gs.push("Three");

    gs.push("Four");


    System.out.println("There are " + gs.size() + " items in the stack.\n");


    System.out.println("The top item is: " + gs.peek() + "\n");


    System.out.println("There are still " + gs.size() + " items in the stack.\n");


    System.out.println("Popping everything:");

    
展开阅读全文