Search code examples
javaarraylistinstances

How to write an ArrayList when instantiating?


Probably I'm being blind or something, but I can't seem to figure out how to do the following:

I have a Class called Shopping with a constructor like this:

Shopping shopping = new Shopping(String name, ArrayList <Shop> shops)

The class Shop is superclass for 4 types of sub-shops, and its constructor is something like this:

Shop shop = new Shop(String name, double area, double income)

My question is: when creating a Shopping instance I don't know what to write on the Array list part of the constructor, like I can create a

Shopping s1 = new Shopping("ABCDE", ?????? <- but don't know what to write here!!!)

Any help?


Solution

  • Explanation

    You create a new instance of the object using

    ArrayList<Shop> shops = new ArrayList<>();
    

    and then you add your stuff

    shops.add(firstShop);
    shops.add(secondShop);
    

    and after that you just pass the variable to the method

    Shopping s1 = new Shopping("ABCDE", shops);
    

    Or if you want to pass an empty list you can simply do it in one line

    Shopping s1 = new Shopping("ABCDE", new ArrayList<>());
    

    Other lists

    Is there a particular reason you need to limit the method to ArrayLists? Wouldn't List be enough too? If you adjust that you can pass other lists too and with Java 9 there is a simple way to create lists quickly:

    List<Shop> shops = List.of(firstShop, secondShop);
    Shopping s1 = new Shopping("ABCDE", shops);
    

    Or even more compact:

    Shopping s1 = new Shopping("ABCDE", List.of(firstShop, secondShop));