Test cases won't work when implementing my own stack - java

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;

Related

Override stack.peek() to return null if the stack is empty

In Java, the peek() method throws an exception if it is invoked on an empty stack.
Currently, to get around this issue, I have to check if the stack isn't empty before calling peek().
Is there a way to override the peek() method so that it returns null whenever a stack is empty instead of throwing an exception?
I think you can simply extend your own version of stack like this:
public class MyCustomStack<E> extends Stack<E> {
#Override
public synchronized E peek() {
if (isEmpty()) {
return null;
}
return super.peek();
}
}
public class OwnStack<E> extends Stack<E> {
#Override
public synchronized E peek() {
int len = size();
if (len <= 0) return null;
return elementAt(len - 1);
}
}
You can do this with any class that is not final in java. Look up inheritance.
public class HackedStack<E> extends Stack<E> {
#Override
public E peek() {
//do your thing
}
}
although you can completely avoid this by using stack#empty
https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html#peek()
public void loop() {
Stack<String> stack = new Stack<>();
while (!stack.empty()) stack.peek();
}
If the stack is accessed by a single thread, you should use a Deque. Not only does its peek() method return null in the empty case, it is also not synchronized and thus faster in single-threaded scenarios.
Deque<T> stack = new ArrayDeque<>();
stack.addFirst(element);
T element = stack.peekFirst();
If the stack is accessed by multiple threads, implementing your own concurrent stack should be preferable in my opinion, and easy if the capacity is fixed.

Why this stack using super.isEmpty()?

Why did I have to invoke super.isEmpty()? I have tried this.isEmpty(), but the debug process is paused.
import java.util.*;
public class Stack<e> extends ArrayList<e> {
/**
*
*/
private static final long serialVersionUID = 1L;
public void showPrompt(){
System.out.println("Please input informations five times and type Enter between each gap:");
}
// `enter code here`
public e peek(){
return get(size()-1);
}
public void push(e o){
add(o);
}
public e pop(){
e o=get(size()-1);
remove (size()-1);
return o;
}
public boolean isEmpty(){
return super.isEmpty();
/* Why did I have to invoke super.isEmpty()? */
}
public String toString(){
return "stack"+toString();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack<String> s=new Stack<>();
s.showPrompt();
Scanner scan=new Scanner(System.in);
for(int i=0;i<5;i++){
s.push(scan.next());
}
System.out.println("Reverse order is:");
while(!s.isEmpty()){
System.out.println(s.pop());
}
}
}
We are talking about this method:
public boolean isEmpty() {
return super.isEmpty();
}
First of all, this method as written is unnecessary1. It is simply calling the isEmpty() method in the superclass; i.e. ArrayList. If you left it out, calls to isEmpty() on a Stack would go directly to the isEmpty() method implemented in the superclass.
Now to your question as to why super is necessary. The answer is that if you don't use super here, and write it like this:
public boolean isEmpty() {
return this.isEmpty(); // INCORRECT!
}
then the isEmpty() method will be calling itself. That causes infinite recursion, and leads to a StackOverflowError. (If you looked at the stacktrace you would see a long sequence of stack frames where isEmpty() calls isEmpty() calls isEmpty() .... and so on. Eventually, you run out of stack space().)
By using super, we are telling Java to call the isEmpty method implemented in the superclass.
1 - This code is not the standard implementation of java.util.Stack. The standard Stack class extends Vector and is doesn't declare an override for isEmpty()

Creating a generic stack in generic stack class

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

implement a queue using two stacks

I think my codes are right, but i do not know why it is not adding elements onto the stack.
Should i create other two stacks in the main?
import java.util.Stack;
public class stacks {
public Stack<Integer> in = new Stack<Integer>();
public Stack<Integer> out = new Stack<Integer>();
public void enqueue(int value){
in.push(value);
}
public int dequeue(){
if (out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
return out.pop();
}
public static void main(String[] args) {
in.enqueue(10);
in.enqueue(49);
}
}
Your code is absolutely correct. You have missed one small thing.
You are pushing elements in stack 1 during enqueue.
During dequeue, you are popping elements from stack 1 and pushing in stack 2. Then you are popping the top element from stack 2 .
(1).
The stuff that you are missing is. Popping all the elements back from stack 2 and pushing them to stack 1. So, here is what I suggest you to do :
public int dequeue(){
if (out.isEmpty())
{
while(!in.isEmpty())
{
out.push(in.pop());
}
}
int outVar = out.pop();
while(!out.isEmpty())
{
in.push(out.pop());
}
return outVar;
}
(2). In the main method. You do not have to create two different stacks. You just have to create an object of you class Stacks. which would solve the purpose.
public static void main(String[] args) {
Stacks obj = new Stacks();
obj.enqueue(10); // Would enqueue 10 in the Stack 1 of the Object 'obj'
obj.enqueue(49);
System.out.println(obj.dequeue());// Would display the dequeued element.
}
Hope this helps.
Your issue here is that you are trying to make a static reference (from the main) to something that isn't static.
Make the following changes:
public static int dequeue()
public static void enqueue(int value)
A workaround to this would be to make an object oriented stack-queue class and then in a separate class make an instance of that stack-queue class. This would eliminate any static referential issues and also bring your program up to par with today's common object-oriented programming standards. Like so:
import java.util.Stack;
public class stacksTest {
public Stack<Integer> in = new Stack<Integer>();
public Stack<Integer> out = new Stack<Integer>();
public void enqueue(int value){
in.push(value);
}
public int dequeue(){
if (out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
return out.pop();
}
}
Then make a new class:
public class Test {
public static void main(String[] args) {
stackTest st = new stackTest();
st.enqueue(10);
st.dequeue(10);
}
}

How can I design a type-safe stack in Java preventing pops from an empty list?

This is an offshoot of these two questions: 1, 2.
I'd like to implement type-safe data structures in Java that prevent nonsensical operations. For example, if the compiler knows I have an instance of an empty stack, it shouldn't allow me to call pop on the empty stack.
As an example, how would I implement such a (generic) stack in Java?
See below Java implementation based on .net code from stakx's question.
If a client tries to pop too far, the compiler will issue an undefined method error. For example, issuing calls like:
new EmptyStack<Integer>().push(1).pop().getTop()
will result in an undefined method error on the call to getTop().
class GenericStack {
#Test public void test() {
final IStack<Integer> stack = new EmptyStack<Integer>();
assertEquals(new Integer(1), stack.push(1).getTop());
assertEquals(new Integer(2), stack.push(1).push(2).getTop());
assertEquals(new Integer(1), stack.push(1).push(2).pop().getTop());
}
interface IStack<T> {
INonEmptyStack<T, ? extends IStack<T>> push(T x);
}
interface IEmptyStack<T> extends IStack<T>
{
#Override INonEmptyStack<T, IEmptyStack<T>> push(T x);
}
interface INonEmptyStack<T, TStackBeneath extends IStack<T>>
extends IStack<T>
{
T getTop();
TStackBeneath pop();
#Override INonEmptyStack<T, INonEmptyStack<T, TStackBeneath>>
push(T x);
}
class EmptyStack<T> implements IEmptyStack<T> {
#Override public INonEmptyStack<T, IEmptyStack<T>> push(T x) {
return new NonEmptyStack<T, IEmptyStack<T>>(x, this);
}
}
class NonEmptyStack<T, TStackBeneath extends IStack<T>> extends Object
implements INonEmptyStack<T, TStackBeneath> {
private final TStackBeneath stackBeneathTop;
private final T top;
NonEmptyStack(T top, TStackBeneath stackBeneathTop) {
this.top = top;
this.stackBeneathTop = stackBeneathTop;
}
#Override public T getTop() {
return top;
}
#Override public TStackBeneath pop() {
return stackBeneathTop;
}
#Override public INonEmptyStack<T, INonEmptyStack<T, TStackBeneath>>
push(T x) {
return
new NonEmptyStack<T, INonEmptyStack<T, TStackBeneath>>(x, this);
}
}
// The following client code at the request of #TacticalCoder demonstrates
// some of the benefits (and limitations) of this implementation.
#Test public void testRandomPopper() {
IStack<?> stack = randomPopper(new EmptyStack<Integer>(), 20);
// This assertion will fail 1 out of .3^20 runs
assertTrue(stack instanceof INonEmptyStack<?,?>);
assertFalse(stack instanceof IEmptyStack<?>);
}
public IStack<Integer> randomPopper(IStack<Integer> s, final int N) {
IStack<Integer> stack;
if(N<1)
return s;
stack = s.Push(1);
for (int i = 1; i < N; i++) {
INonEmptyStack<Integer,?> tStack = stack.Push(i+1);
if(Math.random()<0.3) {
stack = tStack.Pop();
} else {
stack = tStack;
}
}
return stack;
}
#Test public void testDrainStack() {
IStack<Integer> stack = randomPopper(new EmptyStack<Integer>(), 20);
IStack<?> maybeEmptyStack = drainStack(stack);
assertTrue(maybeEmptyStack instanceof IEmptyStack);
IEmptyStack<?> definitelyEmptyStack = (IEmptyStack<?>) maybeEmptyStack;
assertTrue(definitelyEmptyStack instanceof IEmptyStack<?>);
}
#Test public void testCastNonEmptyStackToEmptyStack() {
IStack<Integer> stack = randomPopper(new EmptyStack<Integer>(), 20);
IStack<?> maybeEmptyStack = stack;
assertFalse(maybeEmptyStack instanceof IEmptyStack);
// Below cast should issue warning! Doesn't and issues runtime error.
IEmptyStack<?> definitelyEmptyStack = (IEmptyStack<?>) maybeEmptyStack;
assertFalse(definitelyEmptyStack instanceof IEmptyStack<?>);
}
public IStack<?> drainStack(IStack<?> stack) {
for (;stack instanceof INonEmptyStack<?,?>;)
stack = ((INonEmptyStack<?,?>) stack).Pop();
return stack;
}
}

Categories