Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

java - How to get a method to get and add new objects into an ArrayList?

I only recently started to learn code so forgive me if this is trivial but I can't seem to figure it out, this is a simple assignment for class. Here my professor gave us this and told me to create the checkout class on my own. My question is how could I make the enterItem method in the checkout class to add the "rice" and "baguette" objects into an ArrayList?

public static void main(String[] args) {

        Checkout checkout = new Checkout();

        checkout.enterItem(new Rice("Basmati Rice", 2.25, 399));
        checkout.enterItem(new Baguette("Wheat Baguette", 105));

This is kinda what I have tried but it does not work and I'm not sure why or how to make it work

public class Checkout {
       
    ArrayList items = new ArrayList();
    
    public void enterItem(){
        items.add()
    }
}
question from:https://stackoverflow.com/questions/65835519/how-to-get-a-method-to-get-and-add-new-objects-into-an-arraylist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
checkout.enterItem(new Rice("Basmati Rice", 2.25, 399));

That code is invoking the enterItem method and passing a Rice as an argument.

public void enterItem(){
    items.add()
}

The enterItem method does not accept any arguments, so that won't work. You could do this...

public void enterItem(Rice rice){
    items.add(rice);
}

That will work for Rice, but not for Baguette (unless Baguette extends Rice). You could add 2 versions of enterItem:

public void enterItem(Rice rice){
    items.add(rice);
}

public void enterItem(Baguette bag){
    items.add(bag);
}

If Rice and Bagquette share something above them in the inheritance/implements hierarchy, something like this could work:

public class Baguette implements Edible {}


public class Rice implements Edible {}


public void enterItem(Edible edible){
    items.add(edible);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...