Reputation: 67
I'm fairly new to programming and I'm a bit confused here. I am trying to pass a filled arraylist to another class. Here's the class where I make the 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:
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. Any help is greatly appreciated!
Upvotes: 0
Views: 1572
Reputation: 19
Try decalaring it as instance variable instead of static. and remove static way of accessing the list.
Upvotes: 0
Reputation: 93
The results will not be null or empty. It will have entries as well. If you override toString for the class "engineSpecs " you can see the entries of list.
Upvotes: 0
Reputation: 3212
By default when you print a list it will display it as follows
[ classname of element of 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. In your case the enginespecs class
Adding a simple toString in engineSpecs class like below will give you a desired result
public String toString(){
return name;
}
OUTPUT
[Aston Martin, Ferrari]
NOTE
In java class names need to begin with capital. And a parameter should be declared static only if you want to use it at the class level
Upvotes: 1