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);
创建一个包含Character
对象的堆栈,并在插入它们之前将您char
的 s 转换为。Character
JavaCharacter
类:http ://docs.oracle.com/javase/7/docs/api/java/lang/Character.html
就像int
s 和Integer
s 一样,您需要先包装一个原语,然后才能将其插入数据结构。
编辑:显然Stack
已弃用,因为它继承自Vector
. 原因如下:为什么 Java Vector 类被认为已过时或不推荐使用?
正如马克彼得斯所说,您应该使用LinkedList
or ArrayDeque
。
我决定回答这个问题,因为有一些误解......所以,有String
:
String s = "your string";
创建Stack
或List
( LinkedList
) 查看对 Michael 的回答的评论
Stack<Character> d = new Stack<Character>();
毕竟循环与char
推送逻辑
for (char c : s.toCharArray()) {
d.push(c);
}
仅此而已!