有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ValueStack中存储了哪些对象

下面是我的代码,当我执行它时,它显示大小为3,但当我弹出对象时,我只得到2个对象

import java.util.*;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String name;

    public String execute() throws Exception {
        ValueStack stack = ActionContext.getContext().getValueStack();
        Map<String, Object> context = new HashMap<String, Object>();

        context.put("key1", new String("This is key1"));
        context.put("key2", new String("This is key2"));
        context.put("key3", new String("This is key3"));
        stack.push(context);

        System.out.println("Size of the valueStack: " + stack.size());

        for (int i = 0; i < stack.size(); i++) {
            System.out.println(i + ": " + stack.pop().toString());
        }
        return "success";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
 

请解释一下我是否做错了

Wnd我想知道ValueStack中存储的对象是什么,如何检索这些对象


共 (2) 个答案

  1. # 1 楼答案

    你虐待了context和一张地图

    首先,您得到一个动作contextvalueStack

    然后创建了一个名为context的映射,并将其推送到堆栈中

    然后开始迭代堆栈,但堆栈是另一个对象,它被context压过

    要从堆栈中获取上下文,需要pop()peek()valueStack中获取上下文。然后可以将其作为贴图进行迭代

    代码:

    context = (Map<String, Object>)stack.pop();
    for (Map.Entry<String, Object> entry : context.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
    

  2. # 2 楼答案

    代码中有两个错误,导致无法正确打印结果


    错误n.1

    i <= stack.size()应该是i < stack.size(),否则对于3个元素,您将尝试打印4个元素(i基于0,size()基于1)。
    由于错误n.2,您没有遇到此错误


    错误n.2

    System.out.println(i + ": " + stack.pop().toString());
    

    .pop(): Get the object on the top of the stack and remove it from the stack.

    然后应该在循环之前存储大小,否则堆栈的大小在每次迭代时都会改变

    这就是正在发生的事情:

    for (int i = 0; i <= 3; i++) {
    
    for (int i = 1; i <= 2; i++) {
    
    for (int i = 2; i <= 1; i++) { // not performed. And you don't fall in error n.1.
    

    工作代码

    int size = stack.size();
    
    for (int i = 0; i < size; i++) {
        System.out.println(i + ": " + stack.pop().toString());
    }
    

    这将正确打印结果,但会改变值堆栈;为了避免这种情况,您应该在迭代器中循环值堆栈的对象,您可以使用getRoot()方法获得该迭代器:

    Iterator itr = stack.getRoot().iterator();
    while (itr.hasNext()) {
        System.out.println(itr.next().toString()); 
        // or .getClass().getName(), ReflectionToStringBuilder.toString(), or whatever...
    }