Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to add characters to a stack?

Tags:

java

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!

like image 401
Jay Avatar asked Jan 28 '26 04:01

Jay


2 Answers

Stack<Character> myStack = new Stack<Character>();

char letter = 'a';
myStack.push((Character) letter);

Create a stack that contains Character objects, and cast your chars to Character before you insert them.

Java Character class: http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html

Just like ints and Integers, 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.

like image 152
Michael Avatar answered Jan 29 '26 21:01

Michael


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!!!

like image 26
Sergii Zagriichuk Avatar answered Jan 29 '26 21:01

Sergii Zagriichuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!