import java.util.Iterator;
import java.util.Stack;
public class StackExample {
public static void main(String args[]){
Stack<String> sk = new Stack<String>();
sk.push("Hello");
sk.push("Hello1");
sk.push("Hello2");
sk.push("Hello3");
System.out.println("The Values of Stack" +sk);
Iterator it=sk.iterator();
System.out.println("Size before pop() :"+sk.size());
while(it.hasNext())
{
String iValue=(String)it.next();
System.out.println("Iterator value :"+iValue);
}
String value =(String)sk.pop();
System.out.println("value :"+value);
System.out.println("Size After pop() :"+sk.size());
}
}
任何人都可以向我解释以下问题。
while(it.hasNext()){
String iValue=(String)it.next();
System.out.println("Iterator value :"+iValue);
}
为什么我们要以这种方式迭代以及 hasNext 和 next 的作用是什么 做?我不能用 for 循环做同样的事情吗?
String value =(String)sk.pop();
(String)sk.pop 是什么意思...为什么当我编译时它不编译 删除(字符串)
任何人都可以引导我使用 Java 编写一些好的和复杂的 Stack 示例
最佳答案
广告 1.:这是一个标准的 Java Iterator
.自 Stack
实现者 Iterable
你可以简单地写:
for (String item : sk)
{
System.out.println(item);
}
广告 2.:需要转换为 String
,因为 Iterator
是在没有泛型类型的情况下声明的(这是一种不好的做法)。尝试:
Iterator<String> it=sk.iterator();
不再需要转换。
广告 3.:这是一个在 10 分钟内编写的简单示例:
public static void validateXml(String xml) {
Stack<String> tags = new Stack<String>();
for (String tag : xml.split("\\s"))
if(tag.startsWith("</")) {
if (tags.isEmpty())
throw new IllegalArgumentException("No start tag matching: " + tag);
final String startTag = tags.pop();
if (!startTag.substring(1).equals(tag.substring(2)))
throw new IllegalArgumentException("Start tag: " + startTag + " does not match end tag: " + tag);
} else
tags.push(tag);
if (!tags.isEmpty())
throw new IllegalArgumentException("No end tag matching: " + tags);
}
用法:
validateXml("<a> <b> </b> <c> <d> </d> <e> </e> </c> </a>");
validateXml("<a> <b> </b> <c> <d> <e> </d> </e> </c> </a>"); //fails to validate
关于java - Java 中与 Stack 相关的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7331114/