java - 将 Main 中发生的另一个类文件中启动的数组对象添加到堆栈中

标签 java arrays eclipse object stack

我正在尝试将 Main 中的启动对象(启动发生在 main 中,但从圣诞节类文件中的一个类中提取:courtney.addGift("Dog"); .. 等)放入 myHoliday Stack .

如何将主 Courtney.addGift("Dog") 中的启动对象(addGift 从 Christmas 类文件中拉出)放入 myHoliday 堆栈中?

这是圣诞节文件:

圣诞节

    public class Christmas {

    ArrayList<String> gifts;
    // add a constructor that takes no arguments and initializes
    // the previous properties

    public Christmas()
    {

        gifts = new ArrayList<String>();
    }

    // add a method called addGift that accepts a string
    // and adds it to the gifts data structure
    public void addGift(String gift) 
    {
        gifts.add(gift);
    }

}

主要

 public static void DemoChristmas()
    {
    // create a couple of Christmas objects and add them to a stack
    //Pop them off the stack and print them as you go 

        Christmas courtney = new Christmas();
        Christmas alexandra = new Christmas();
        Christmas bobby = new Christmas();
        Christmas jackie = new Christmas();

        Stack<Christmas> myHoliday = new Stack<Christmas>();

        // initiate the Christmas objects 
        courtney.addGift("Dog");
        alexandra.addGift("Hat");
        jackie.addGift("Car");
        bobby.addGift("Socks");
        // add them to the stack

    }

最佳答案

  1. 在您的圣诞节类(class)中制作合适的 gettersetter
  2. 如果您想打印 stack 的内容,您需要重写 Christmas 类的 toString()
class Christmas {
    private ArrayList<String> gifts;

    public Christmas() {
        gifts = new ArrayList<String>();
    }

    public void addGift(String gift) {
        gifts.add(gift);
    }

    public ArrayList<String> getGifts() {
        return gifts;
    }

    public void setGifts(ArrayList<String> gifts) {
        this.gifts = gifts;
    }

    @Override
    public String toString() {
        StringBuilder giftName = new StringBuilder();
        for (String gift : gifts){
            giftName.append(gift);
            giftName.append(" ");
        }
        return giftName.toString().trim();
    }
}

此外,这不是打印堆栈的正确方法。

private static void printStack(Stack<Christmas> stack) {
    while (!stack.isEmpty()) System.out.println(stack.pop());
}

可能是一种方式。

关于java - 将 Main 中发生的另一个类文件中启动的数组对象添加到堆栈中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58982870/

相关文章:

java - 将另一个 Activity 的数据显示到另一个 Activity 。动态地从类到数组列表到线性布局

java - ActionContext.getContext().getSession() 返回 null

java - 无法将 mysql 驱动程序与 Wildfly 9.0.2 一起使用,但它似乎已正确加载

php - MongoDB 组数组值是否存在检查

javascript - 如何获取 JSON key :value pair 的路径

PHP 和(太多)输入字段

java - 了解 float 和无限循环

java - CSS 无法连接到 .jsp 文件(使用 STS)

java - Eclipse 中的数据 GridView

java - 如何检查哪些用户正在访问我在 eclipse 中运行的 tomcat 服务器(java web 开发)?