Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Oriented adding items to an a arrayList

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);
    }
}
like image 791
sodawimps Avatar asked Apr 15 '26 09:04

sodawimps


1 Answers

Your addItem method takes an item, so the second snippet won't work, at least not with the implementation of ItemList being what it is. You could of course add it to your class:

public void addItem(String name, double weight, double price) {
    itemList.add(new Item(name, weight, price));
}

There is an argument to be made here that implementing ItemList like that hides the Item class from whoever uses ItemList - this may or may not be appropriate, depending on how you intend these two class to be used.

like image 113
Mureinik Avatar answered Apr 16 '26 23:04

Mureinik