我试图在Main中获取已初始化的对象(该初始化发生在Main中,但它是从Christmas类文件中的一个类中提取的:Courtney.addGift(“ Dog”); ..等)到myHoliday Stack中。

我如何在main 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

    }

最佳答案

在圣诞节课上,选择合适的getterssetters
如果要打印stack的内容,则需要覆盖圣诞节课程的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());
}


可能是一种方法。

08-26 21:01