The GenStack Class : Generic Collection « Generics « Java






The GenStack Class

    


import java.util.LinkedList;

class GenStack<E> {
  private LinkedList<E> list = new LinkedList<E>();

  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();
  }

  public int size() {
    return list.size();
  }
}

public class GenStackTest {
  public static void main(String[] args) {
    GenStack<String> gs = new GenStack<String>();

    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:");

    while (gs.hasItems())
      System.out.println(gs.pop());
    System.out.println("There are now " + gs.size() + " items in the stack.\n");
    System.out.println("The top item is: " + gs.peek() + "\n");
  }
}

   
    
    
  








Related examples in the same category

1.Creating a Type-Specific List
2.A list declared to hold objects of a type T can also hold objects that extend from T.
3.A value retrieved from a type-specific list does not need to be casted
4.Generic ArrayListGeneric ArrayList
5.Generic Data Structure
6.Unchecked Example
7.Generic StackGeneric Stack
8.Enum and GenericEnum and Generic
9.Generic HashMapGeneric HashMap
10.Foreach and generic data structureForeach and generic data structure
11.Pre generics example that uses a collection.Pre generics example that uses a collection.
12.Data structure and collections: Modern, generics version.Data structure and collections: Modern, generics version.
13.Java generic: Generics and arrays.
14.Collections and Data structure: the generic wayCollections and Data structure: the generic way
15.Create a typesafe copy of a raw set.
16.Create a typesafe copy of a raw list.
17.Create a typesafe copy of a raw map.
18.Create a typesafe filter of an unchecked iterator.
19.Create a typesafe view over an underlying raw set.
20.Create a typesafe view over an underlying raw map.
21.Create a typesafe filter of an unchecked enumeration.
22.Circular Object Buffer
23.A collection that do not hold stored elements in memory, but serialize it into a file
24.Generic Triple structure
25.Generic Pair
26.A generic bag of properties used to store properties that apply to a specific target.
27.Pool container