我正在尝试将 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
}
最佳答案
- 在您的圣诞节类(class)中制作合适的
getter
和setter
- 如果您想打印
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/