简体   繁体   English

将arraylist传递给另一个类

[英]Passing an arraylist to another class

I'm fairly new to programming and I'm a bit confused here. 我是编程新手,在这里我有点困惑。 I am trying to pass a filled arraylist to another class. 我正在尝试将填充的arraylist传递给另一个类。 Here's the class where I make the arraylist: 这是我制作arraylist的类:

public class inventory
{    
    private static ArrayList<engineSpecs> list = new ArrayList<engineSpecs>();
    public inventory()
    {        
        //Instantiates objects of constructor engineSpecs
        engineSpecs astonmartin = new engineSpecs("Aston Martin", "Vanquish", 350000, 11, "Gray",
                                     2015, 565, 457, "automatic");
        engineSpecs ferrari = new engineSpecs ("Ferrari", "458 Italia", 240000, 13, "Red", 2015, 
                                       570, 398, "automatic"); 

        //Adds objects into array list
        list.add(astonmartin);
        list.add(ferrari);   
    }
    public static ArrayList<engineSpecs> getList()
    {
        return list;
    } 
}

And here's the class I'm trying to pass the arraylist to: 这是我试图将arraylist传递给的类:

public class Main
{
    public static void main (String[] args)
    {        
    inventory inventory = new inventory();
    System.out.println (inventory.getList());
    }
}

When I run the main class, it just prints out an empty arraylist. 当我运行主类时,它只是打印出一个空的arraylist。 Any help is greatly appreciated! 任何帮助是极大的赞赏!

By default when you print a list it will display it as follows 默认情况下,当您打印列表时,它将显示如下

[ classname of element of list@HashCode ] [list @ HashCode的元素的类名]

If you want a list to be displayed in a specific way you need to override the toString method of the class which is added to the list. 如果要以特定方式显示列表,则需要覆盖添加到列表中的类的toString方法。 In your case the enginespecs class 在您的情况下,enginespecs类

Adding a simple toString in engineSpecs class like below will give you a desired result 在下面的engineSpecs类中添加一个简单的toString会给您期望的结果

public String toString(){
return name;
}

OUTPUT 输出值

[Aston Martin, Ferrari] [阿斯顿·马丁,法拉利]

NOTE 注意

In java class names need to begin with capital. 在Java中,类名必须以大写开头。 And a parameter should be declared static only if you want to use it at the class level 并且仅当您想在类级别使用参数时,才应将其声明为静态

The results will not be null or empty. 结果将不会为null或为空。 It will have entries as well. 它将也有条目。 If you override toString for the class "engineSpecs " you can see the entries of list. 如果您为类“ engineSpecs”覆盖toString,则可以看到列表的条目。

Try decalaring it as instance variable instead of static. 尝试将其标为实例变量而不是静态。 and remove static way of accessing the list. 并删除访问列表的静态方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM