I am creating this stack class with the following methods as shown .
import java.util.ArrayList;
import java.util.EmptyStackException;
public class SortableStack<E extends Comparable<E>> implements ISortableStack<E> {
private int N;
private Node first;
private class Node {
private E e;
private Node next;
}
public SortableStack() {
first = null;
N = 0;
}
private ArrayList<E> listOne = new ArrayList<E>();
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public void push(E e) {
Node oldfirst = first;
first = new Node();
first.e = e;
first.next = oldfirst;
N++;
}
public E pop() {
if (isEmpty()) throw new RuntimeException("Stack underflow");
E e = first.e; // save e to return
first = first.next; // delete first node
N--;
return e; // return the saved e
}
public E peekMidElement() {
if(listOne.size() <= 0){
throw new EmptyStackException();
}
return listOne.get(listOne.size()/2);
}
public E peekHighestElement() {
if(listOne.size() <= 0){
throw new EmptyStackException();
}
return listOne.get(listOne.size() - 1);
}
public E peekLowestElement() {
if(listOne.size() <= 0){
throw new EmptyStackException();
}
return listOne.get(0);
}
}`
//The interface ISortableStack is [here][1]
(The comments describe the required method signatures).
[1] :http://stackoverflow.com/questions/7130901/java-stack-implementation
Now when I try to create the main body class as here :
import java.io.*;
public class ExhibitStack<E extends Comparable<E> > {
E ch;
public static void main(String[] args) throws IOException {
ISortableStack<E> s = new ISortableStack(5); // Cannot instatiate ISORTABLESTACK
ExhibitStack demo = new ExhibitStack();
// Cannot make reference to a non static type
while ((demo.ch = (E) System.in.read()) != '\n') {
if (!s.full()) {
s.push(demo.ch);
}
}
while (!s.empty()) {
System.out.print(s.pop());
}
System.out.println();
}
}
It throws error at ISortableStack as:Cannot make a reference to a non static type .
and is not able to instatiate the ISORTABLESTACK
I would like to create the menu driven program using the interface. I am bad at Java GENERICS and collections and have been pretty late on submitting the assignment .
Any help/directions would be much appreciated.
ISortableStackis an interface (it specifies the signatures of methods but not the code that goes in those methods) and thus it can’t itself be instantiated. Instead try using your concrete implementation class:Now,
EinSortableStackis a type parameter: it’s a placeholder for some specific class, likeString. Instead of specifyingEas the user of this class, you need to tell the compiler whatEshould map to for this instance. It looks like your stack needs to hold characters, so what you really want is:You don’t need
chto be a member ofdemo.