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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:13:51  来源:igfitidea点击:

is there a way to add characters to a stack?

java

提问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 Characterobjects, and cast your chars to Characterbefore you insert them.

创建一个包含Character对象的堆栈,并在插入它们之前将chars 转换为Character

Java Characterclass: 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 ints and Integers, you need to wrap a primitive before you can insert it in to a data structure.

就像ints 和Integers 一样,您需要先包装一个原语,然后才能将其插入到数据结构中。

Edit: Apparently Stackis 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 LinkedListor ArrayDeque.

正如 Mark Peters 指出的那样,您应该使用LinkedListArrayDeque

回答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 Stackor List(LinkedList) look to comment to Answer from Michael

创建StackList( LinkedList) 看评论迈克尔的回答

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

after all loop with charpush logic

毕竟循环char推逻辑

 for (char c : s.toCharArray()) {
        d.push(c);
    }

And that is all!!!

这就是全部!!!