Reputation: 23
I have a stack, and it reads forwards and backwards. I need to be able to input arbitrary values instead of using integer (i) --- how would I go about doing this? Would I use an array?
package stacking;
import java.util.*;
/**
* @author Blood Fox
* 2/11/2015
* Stack Class - Learning how to use "Stack" Interfaces.
*
*/
public class StackMain {
//@param args
public static void main(String[] args) {
// Create a new, empty stack
Stack<Integer> stack = new Stack<Integer>();
Integer reversedStack = null;
Integer forwardsStack = null;
//add some items to it
System.out.println("This is forwards:");
for (int i = 0; i <= 0; i++)
{
//stack.push ( new Integer(i) );
forwardsStack = stack.push( new Integer(i));
System.out.print (i + " " );
}
// Last in first out means reverse order - reverse and place it in reversedStack
System.out.println("");
System.out.println("This is backwards:");
//do a loop for while empty --- remove
while ( !stack.empty() )
{
reversedStack = stack.pop();
System.out.print(reversedStack);
System.out.print (" " );
}
//compare both values of the forward and backward values to match and see if it's a palindrome.
if (forwardsStack == reversedStack)
{
System.out.println("");
System.out.println("The stack is a palindrome");
}
if (forwardsStack != reversedStack)
{
System.out.println("");
System.out.println("The stack is NOT a palindrome");
}
// Empty, let's lift off!
System.out.println("");
System.out.println("The stack is now empty");
}
}
I was thinking about using an integer startVal, and an array, to place the forwardsStack correctly on the original number stack. How would I go about doing this?
Upvotes: 0
Views: 99
Reputation: 27986
There are a few points worth making here:
Stack<Object>
to allow objects of any type to be added to your stack. This is because all classes are subclasses of Object
.Object
as the type of your collection is a bad idea. It's normally misused to allow a collection to contain objects from completely different domains with instanceof
and casts used to handle members. Instead it's normally better to declare an interface
which all members will implement.equals
method is part of the Object
class so you will be able to do exactly what you need to do with the Object
members. This makes it one of the (few) situations in which declaring a Stack<Object>
may be appropriate.==
. This will not do what you want. It merely checks if the two variables refer to the same object which they do not. You should use forwardsStack.equals(reversedStack)
. This correctly compares both the size of the stacks and each member using equals
.Upvotes: 1