I'm new to object orientated languages and just have a few questions about adding items to an ArrayList. I've come up with a solution however I'm confused as I've seen another method used which I don't understand. Could someone please explain to me how the second method works?
I have two classes one for an item in a shop:
public class Item {
String name;
double weight;
double price;
public Item(String itemName,double itemWeight, double itemPrice){
this.name = itemName;
this.weight = itemWeight;
this.price = itemPrice;
}
public String toString(){
return(name + " has a weight of " + weight + " and a price of " + price);
}
}
And another of an arraylist of items in the shop:
import java.util.ArrayList;
public class ItemList{
String itemName;
ArrayList<Item> itemList = new ArrayList<>();
public ItemList(String name) {
itemName = name;
}
public void addItem(Item item1){
itemList.add(item1);
}
public void printItems(){
for(int i=0; i < itemList.size(); i++){
System.out.println(itemList.get(i));
}
}
}
I then have a main method that adds items to the list then prints them:
public class ShopMain {
public static void main (String[] args){
ItemList myList = new ItemList("Fruit");
Item apple = new Item("Apple", 100, 60);
myList.addItem(apple);
Item banana = new Item("Banana", 118, 50);
myList.addItem(banana);
myList.printItems();
}
}
However the second method I've seen people use doesn't work for me and is formatted like this:
public class HopefulShopMain{
public static void main (String[] args){
ItemList myList = new ItemList("Fruit");
myList.addItem("Apple", 100, 60);
myList.addItem("Banana", 118, 50);
}
}
ItemListclass:public void addItem(String itemName,double itemWeight, double itemPrice) { itemList.add(new Item (itemName, itemWeight, itemPrice));}