Is there a way to add characters from a string to a stack without having to create your own push and pop methods?
Examples would be very appreciated!
Is there a way to add characters from a string to a stack without having to create your own push and pop methods?
Examples would be very appreciated!
Stack<Character> myStack = new Stack<Character>();
char letter = 'a';
myStack.push((Character) letter);
Create a stack that contains Character
objects, and cast your char
s to Character
before you insert them.
Java Character
class: http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html
Just like int
s and Integer
s, you need to wrap a primitive before you can insert it in to a data structure.
Edit: Apparently Stack
is deprecated since it inherits from Vector
. Here's why: Why is Java Vector class considered obsolete or deprecated?
As Mark Peters indicated, you should use LinkedList
or ArrayDeque
.
I've decided to answer to this question because there are some misunderstanding...
So,
There is String
:
String s = "your string";
Create Stack
or List
(LinkedList
) look to comment to Answer from Michael
Stack<Character> d = new Stack<Character>();
after all loop with char
push logic
for (char c : s.toCharArray()) {
d.push(c);
}
And that is all!!!