java 有没有办法将字符添加到堆栈中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14430996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is there a way to add characters to a stack?
提问by Jay
Is there a way to add characters from a string to a stack without having to create your own push and pop methods?
有没有一种方法可以将字符串中的字符添加到堆栈中,而无需创建自己的 push 和 pop 方法?
Examples would be very appreciated!
示例将不胜感激!
回答by Michael
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.
创建一个包含Character
对象的堆栈,并在插入它们之前将char
s 转换为Character
。
Java Character
class: http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html
JavaCharacter
类: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.
就像int
s 和Integer
s 一样,您需要先包装一个原语,然后才能将其插入到数据结构中。
Edit: Apparently Stack
is deprecated since it inherits from Vector
. Here's why: Why is Java Vector class considered obsolete or deprecated?
编辑:显然Stack
已弃用,因为它继承自Vector
. 原因如下:为什么 Java Vector 类被认为已过时或已弃用?
As Mark Peters indicated, you should use LinkedList
or ArrayDeque
.
正如 Mark Peters 指出的那样,您应该使用LinkedList
或ArrayDeque
。
回答by Sergii Zagriichuk
I've decided to answer to this question because there are some misunderstanding...
So,
There is String
:
我决定回答这个问题,因为有一些误解......所以,有String
:
String s = "your string";
Create Stack
or List
(LinkedList
) look to comment to Answer from Michael
创建Stack
或List
( LinkedList
) 看评论迈克尔的回答
Stack<Character> d = new Stack<Character>();
after all loop with char
push logic
毕竟循环char
推逻辑
for (char c : s.toCharArray()) {
d.push(c);
}
And that is all!!!
这就是全部!!!