如何获取(外部)类对象以将值存储在当前的类集合中?

时间:2019-07-18 17:25:58

标签: java generics

我已经能够创建一个对象来从单独的类中调用方法,但是我还没有弄清楚如何使用那些set / get方法并将其存储在当前的类集中。帮助吗?

现在,它将字符串存储在我的class对象中。我知道这显然不是它的外观,但我不知道如何格式化将此逻辑存储到我的foodList ArrayList中的正确语句。

import java.util.ArrayList;

public class GenericStackApp {

    public static void main(String[] args) {

        // This creates a new ArrayList with String type elements
        ArrayList<String> foodList = new ArrayList<>();

        // This creates an object, to enable the program to use the methods
            // from the other Stack class and keeping this code cleaner
        Stack stack = new Stack();

        // This calls the addElement method from the Stack class, and passes
            // a the String as an argument. I obviously have no issue using
            // this external method, the issue for me was actually assigning
            // the values of each added element to the existing foodList 
            // ArrayList I initially created.
        stack.addElement("Apples");
        stack.addElement("Oranges");
        stack.addElement("Bananas");

        // This is the code that would be used to display each element, had
            // they been added correctly to the foodList ArrayList. Otherwise,
            // this is just meaningless code for now.
        for (String fruit : foodList) {
            System.out.println(foodList);
        }

        // This provides the actual size of the ArrayList. What's strange to me
            // is notice the getSize method is called and returns the size of the
            // linkedList
        System.out.println("The stack contains " + stack.getSize() + " items.");

        // This is code that would have grabbed a peek into the last element
            // of the foodList, had they been added to this collection correctly
        stack.lastElement();
        for (String fruit : foodList) {
                System.out.println(foodList);
            }

        System.out.println("The stack contains " + stack.getSize() + " items.");

        // This removes the last element in the list, one by one. The console
            // output provides a String summarizing each action.
        stack.removeElement();
            System.out.println(foodList + " has been removed.");
        stack.removeElement();
            System.out.println(foodList + " has been removed.");
        stack.removeElement();
            System.out.println(foodList + " has been removed.");

        System.out.println("The stack contains " + stack.getSize() + " items.");

    }
}

我希望控制台输出我添加和删除的元素。

0 个答案:

没有答案