Creating a generic stack in generic stack class - java

I'm trying to teach myself some java and im stuck on a problem that seems kind of easy but i still don't seem to find a solution.
What I have so far:
Interface:
public interface ADTStack<T> {
public boolean isEmpty();
public void push(T element);
public T top() throws IllegalStateException;
public void pop() throws IllegalStateException;
}
Class Stack:
public class Stack<T> implements ADTStack<T> {
private java.util.LinkedList<T> data;
public Stack() {
data = new java.util.LinkedList<T>();
}
#Override
public boolean isEmpty() {
return data.isEmpty();
}
#Override
public void push(T element) {
data.add(0, element);
}
#Override
public T top() throws IllegalStateException {
if (isEmpty()) {
throw new IllegalStateException("Stack is emtpy.");
}
return data.getFirst();
}
#Override
public void pop() throws IllegalStateException {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty.");
}
data.remove(0);
}
Alright , so here is what I'm trying to do.
I'm trying to write a methode equals to compare two Stacks.
My idea was to use a third Stack to be able to bring both stacks into
their original state after comparing them.
Here's what I have:
Stack supportStack = new Stack();
public boolean equals(ADTStack<T> s){
if (data.isEmpty() != s.isEmpty()){
return false;
}
if (data.isEmpty() && s.isEmpty()){
return true;
}
T element_a = this.top();
T element_b = s.top();
if( (element_a ==null && (element_b !=null) || !element_a.equals(element_b) || element_a != null && element_b == null)){
return false;
}
data.pop();
s.pop();
supportStack.push(element_a);
boolean result = data.equals(s);
while (!supportStack.isEmpty()){
data.push(supportStack.top());
s.push(supportStack.top());
supportStack.pop();
}
return result;
}
I get a lot of errors when I compile the code and it seems that something is wrong with :
Stack supportStack = new Stack();
I don't really know what's wrong and how to solve the error. I made a runner-class and I tried the constructor and it worked so I'm confused at what's wrong.
public class Runner {
public static void main(String[] args){
Stack test = new Stack();
test.push(12);
System.out.println(test.top());
}
}
I gladly take any advice or constructive criticism since I'm teaching myself and if anything seems unclear feel free to ask.

Stack supportStack = new Stack();
Stack is called a raw type: it's like not using generics. You need to use:
Stack<T> supportStack = new Stack<T>();
But, as a hint: you don't need to do this. You can just do:
return this.data.equals( s.data );

Related

Test cases won't work when implementing my own stack

So our homework was to implement a stack on our won and then write test cases for it.
This is the stack:
import java.util.Vector;
class Stack<T> extends Vector<T> {
private Vector<T> stack;
Stack() {
stack = new Vector<T>();
}
// returns false or true, given the stack is empty or not.
public boolean isEmpty() {
return stack.size() == 0;
}
//returns the top element of the stack without removing it.
public T peek() {
return stack.get(stack.size()-1);
}
//puts a new element to the top of the stack
public void push(T element) {
stack.add(element);
}
//returns and removes the top element of the stack
public T pop() {
return stack.get(stack.size()-1);
}
}
And this is my test class so far.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StackTest {
#Test
void isEmpty() {
stack s = new stack<Integer>;
assertEquals(true, s.isEmpty());
}
#Test
void peek() {
Stack t = new Stack(1);
}
#Test
void push() {
}
#Test
void pop() {
}
}
I am really having trouble figuring out what is wrong with the first two test methods. Does anybody else have an idea?
This is wrong:
//returns and removes the top element of the stack
public T pop() {
return stack.get(stack.size()-1);
}
You don't remove the element, use remove instead of get
Other errors:
void isEmpty() {
//Typo errors here, s is uppercase and missing parenthesis
stack s = new stack<Integer>;
assertEquals(true, s.isEmpty());
}
#Test
void peek() {
//What does Stack(1) mean? There is no such constructor in class
Stack t = new Stack(1);
}
Also:
//If you already extend Vector you don't need a Vector field for the data
class Stack<T> extends Vector<T> {
private Vector<T> stack;

Cannot infer type arguments for Generic Class

I am trying to create Expression Tree using the Postfix Expression.
This needs a Stack which could hold Tree Objects.
I created a generic Stack class which could except <TreeTemp> as type argument.
On trying to initialize the stack with following statement, its giving "Cannot infer type arguments for TreeStack<>" error.
private TreeStack<TreeTemp> stack1 = new TreeStack<>(new TreeTemp());
Stack Class:
public class TreeStack<T> {
private T [] stackElem;
private final int MAXSTACKSIZE;
private int top;
public TreeStack(Class<T> t) {
top = -1;
MAXSTACKSIZE = 20;
final T[] stackElem = (T[]) Array.newInstance(t, MAXSTACKSIZE);
this.stackElem = stackElem;
}
public void push(T elem) throws Exception{
if(isFull()) {
stackElem[++top] = elem;
}
else
throw new Exception("Stack is already Full");
}
public T pop() throws Exception {
if(isEmpty()) {
return stackElem[top--];
}
else
throw new Exception("Stack is Empty");
}
public boolean isEmpty() {return top == -1;}
public boolean isFull() {return top==MAXSTACKSIZE-1;}
}
Postfix.class(Class having method for creating tree)
public class PostFix {
private String expression = new String("A*B+C");
private char [] expElem = expression.toCharArray();
/*Error on below Statement*/
private TreeStack<TreeTemp> stack1 = new TreeStack<>(new TreeTemp());
public TreeTemp makeTree() throws Throwable {
try {
for(int i=0;i<expElem.length;i++) {
ExpNode eNode = new ExpNode();
eNode.setiData(expElem[i]);
TreeTemp t = new TreeTemp();
t.setRoot(eNode);
if(!Character.isLetter(expElem[i])) {
t.setLeftTree(stack1.pop());
t.setRightTree(stack1.pop());
}
stack1.push(t);
}
return stack1.pop();
}catch (Exception e) {
throw new Exception("Stack Error while creating a Tree", e);
}
}
public static void main(String[] args) throws Throwable {
PostFix pf = new PostFix();
TreeTemp t = pf.makeTree();
}
Tree Class(Type which i want to add into Stack):
public class TreeTemp {
private ExpNode root;
private TreeTemp leftTree;
private TreeTemp rightTree;
/*public TreeTemp(ExpNode expNode) {
root = expNode;
}*/
public TreeTemp getLeftTree() {
return leftTree;
}
public void setLeftTree(TreeTemp leftTree) {
this.leftTree = leftTree;
}
public TreeTemp getRightTree() {
return rightTree;
}
public void setRightTree(TreeTemp rightTree) {
this.rightTree = rightTree;
}
public ExpNode getRoot() {
return root;
}
public void setRoot(ExpNode node) {
this.root = node;
}
}
Can someone pls give some pointers.
Your TreeStack has only one constructor. Here it is:
public TreeStack(Class<T> t) {
Thus, to invoke it, you need to pass the class object that represents the class associated with the T type. So, the class itself, not 'some particular instance of T'. When you call it on your error line:
private TreeStack<TreeTemp> stack1 = new TreeStack<>(new TreeTemp());
You are passing an instance of TreeTemp. Not the concept 'TreeTemp, the class'. Try new TreeStack<>(TreeTemp.class);
Note that as a general rule, passing a Class<T> is a code smell; you're trying to make generics something that it isn't (you're trying to runtime reify). This is objectively bad: It means you can't make a TreeStack<List<String>>, for example, because you're restricted to the overlap where both generics as well as j.l.Class instances can represent the thing, and that's just simple, non-genericsed, non-primitive classes.
final T[] stackElem = (T[]) Array.newInstance(t, MAXSTACKSIZE);
Looks like the only reason you want that class is to make sure your array is properly typed.
This is not neccessary. Just make a new Object[] array, and cast to T anytime you need to return a T. Now your TreeStack constructor needs no arguments at all.
Check the source of java.util.ArrayList, which agrees with this assessment; it is backed by an Object array, not a T[].
The TreeStack constructor accepts a Class<T>, not a T, so you should do:
new TreeStack<>(TreeTemp.class);
Since this is an exercise to create expression trees, you don't really need to implement stacks from scratch. You should just use the ArrayDeque class through the Deque interface in the Java Collections API.
private Deque<TreeTemp> stack1 = new ArrayDeque<>();
Deque has all the methods your TreeStack has, and many more.

Simple Stack, how to initialize Node at 0 instead of null

I am trying to implement a very simple stack, however, it seems that I need to use a node for this. I have the below which compiles and works fine, however, it throws a lot of errors until someone makes the first push. I am in a situation where I cannot control what is in the consumer's main method, so I think it would be best to avoid these errors and just initialize a new stack object with an initial value of zero. Unfortunately, I cannot figure out just how to do that. Would anyone here be able to advise me?
import java.util.*;
public class StackQ {
Node top;
public StackQ() {
top=null;
}
class Node {
public int x = 0;
public Node next;
Node(int d) {x=d; next=null;}
public int getData() {return x;}
}
public int pop() {
if(top!=null) {
int item = top.x;
top = top.next;
return item;
}
return -1;
}
public void push(int x) {
Node t = new Node(x);
t.next = this.top;
this.top = t;
}
public int top() {
if (top == null) throw new EmptyStackException();
return top.x;
}
public static void main(String[] args) {
StackQ mainStack = new StackQ();
}
}
If they're using top() without putting anything in the stack, they are using your stack wrong. Seriously, they should be getting an exception. It's up to them to not use your stack that way, and it's up to them to properly handle that exception.
But if you really wanted to always start your stack with a 0 in it (which, to be perfectly clear, I am advising against doing) just put that in your constructor.
public StackQ() {
top=new Node(0);
}

Get call in stack Java

public void push(E e)
{
list.add(e);
}
public E pop()
{
list.remove(list.size()-1);
}
public E peek()
{
}
public boolean empty()
{
if ( list.size()== 0)
{
return false;
}
else
{
return true;
}
}
This is part of a driver code my teacher gave me in order to under stand the stack. I understand what each part of the stack does, I am just not understanding how to implement the stack based on this code. I need help with the peek method mainly, but if you see other issues please let me know. I would appreciate the help.
public E peek(){
if(empty()) return null;
int top = list.size()-1;
return list.get(top);
}
AND empty method can be simplifized to:
public boolean empty(){
return list.size() == 0;
}
OR
public boolean empty(){
return list.isEmpty();
}
AND pop method should throws NoSuchElementException when stack is empty.
public E pop(){
if(empty()) throw new NoSuchElementException();
int top = list.size()-1;
return list.remove(top);
}

exception handling in parentheses matching using stacks in java

I am trying to write a program that checks for parentheses matching using stacks.This is my ArrayStack class.
public class ArrayStack{
private final int DEFAULT_SIZE=10;
public int tos;
Object[] array;
public ArrayStack(){
array =new Object[DEFAULT_SIZE];
tos=-1;
}
public void push(Object e)throws OverFlowException{
if (isFull()){
throw new OverFlowException("OverFlow");
}
else{
array[tos+1]=e;
tos++;
}
}
public Object topAndpop() throws EmptyStackException{
Object returnPop;
if (isEmpty())
throw new EmptyStackException("Stack empty");
else{
returnPop=top();
pop();
}
return returnPop;
}
public void pop() throws EmptyStackException{
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
tos--;
}
public Object top() throws EmptyStackException{
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
return array[tos];
}
public boolean isEmpty(){
return tos==-1;
}
public boolean isFull(){
if(tos==array.length)
return true;
else
return false;
}
public void makeEmpty() throws EmptyStackException{
while (tos>=0){
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
pop();
}
}
public void print(){
for (int i=0;i<=tos;i++){
System.out.println(array[i]);
}
}
public static void main (String args[]) throws EmptyStackException,OverFlowException {
ArrayStack newStack=new ArrayStack();
newStack.push("S");
newStack.push("apple");
newStack.push("D");
newStack.topAndpop();
newStack.push("P");
newStack.print();
}
}
And this is my matching class.
public class Matching{
ArrayStack match_Stack=new ArrayStack();
Object popped;
Object[] array_match={"{","}"};
public boolean matching() {
for(int i=0;i< array_match.length;i++){
if (array_match[i]=="{" || array_match[i]=="[" ||array_match[i]=="(" )
match_Stack.push(array_match[i]);
if(array_match[i]=="}" || array_match[i]=="]" || array_match[i]==")"){
if (match_Stack.isEmpty())
return false;
if (match_Stack.topAndpop()==array_match[i]);
return true;
}
}
if (match_Stack.isEmpty())
return true;
else
return false;
}
public static void main (String args[]) throws EmptyStackException,OverFlowException {
}
}
This is EmptyStackException class :
public class EmptyStackException extends Exception{
public EmptyStackException(){
super();
}
public EmptyStackException(String s){
super(s);
}
public void print(){
System.out.println("OverFlow");
}
}
But the problem is when I compile matching I get an error as unreported exception EmptyStackException.must be caught or declared to be thrown.
I think the problem is with exceptions which I don't have a good knowledge of.I am stuck here for days and because of this exception issue I am unable to study the rest of data structures. So any help on how I can fix this and run this would be greatly helpful.
You really should read a tutorial about exceptions and work it through completely. This way you will get a better understanding of exceptions.
Your problem is the method Matching.matching(). You are using the methods ArrayStack.push(Object) and ArrayStack.topAndpop() in the method's implementation. But these methods are declared to (potentially) throw an EmptyStackException.
Your matching method does not deal with that exception. The exception must be either caught or thrown. This is what the compiler does tell you. So for a first coming-through declare the method as
public boolean matching() throws EmptyStackException

Categories