2

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!

Jay
  • 185
  • 2
  • 7
  • 21

2 Answers2

8
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.

Community
  • 1
  • 1
Michael
  • 3,334
  • 20
  • 27
3

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

Sergii Zagriichuk
  • 5,389
  • 5
  • 28
  • 45