Wednesday, February 16, 2011

Homework #1.4

Modify your code from 1.3 to make use of the Queue<T> interface.

Unfortunately, there does not seem to be a Stack<T> interface, just a Stack<T> class. They recommend using the Deque interface and calling the associated stack methods instead of this Stack class. However, I don't want you to have to implement every single method associated with a Deque interface. Instead, implement the superinterface to Deque, which is java.util.Queue<T>.

Certain inherited methods from the superinterface Collection it does not make sense to implement. For example, why get an iterator? The rules for a stack are such that we can only see the top element. The same for the contains method. Therefore, only focus on the ones that are directly mentioned in the documentation for Queue, except, mentally substitute stack for queue:


Method Summary
 booleanadd(E e)
          Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
 Eelement()
          Retrieves, but does not remove, the head of this queue.
 booleanoffer(E e)
          Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
 Epeek()
          Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
 Epoll()
          Retrieves and removes the head of this queue, or returns null if this queue is empty.
 Eremove()
          Retrieves and removes the head of this queue.


In addition, the following from the superinterface Collection makes sense to implement:


Methods inherited from interface java.util.Collection
addAllclearequalsisEmptysizetoArraytoArray

2 comments:

  1. professor how do i make addAll method? i mean i tried it and didnt work. how do i get collection from user lets say since im doing it with GUI. i cant make a collection of integers that need to be added to the stack right?

    ReplyDelete
  2. well, for your Driver, you can just make up a collection of five random Integers (or all with the number 10), and then call the appropriate method to add them. you don't have to prompt the user for the specific values.

    here, btw, is a tutorial on using collections.
    http://www.learn-java-tutorial.com/Java-Collections.cfm

    ReplyDelete