Search code examples
javalistobjectmethodsmain-method

How to create an object of List from another class in main method?


I have to create an Object of List in main Method but i have no idea how to do it. Constructor of class, that i want to create an Object has an List as a parameter.

How can i create an Object of CashMachine class?

By the way I am not going to write all of the classes, because it is long.

Here are my classes:

    public class CashMachine {
        private State state;
        List<Account> accountList;
        private CashCard cashCard;
        private Account selectedAccount;

        public CashMachine(List<Account> accountList){
            this.accountList = accountList;
        }
    }

public class TestMain {
    public static void main(String[] args) throws Exception {
        CashMachine cashMachineObj = new CashMachine(); //it is false

    }
}

Solution

  • You wrote a constructor, that wants a List ... so surprise, you have to provide one.

    Simple, will compile, but is wrong:

    CashMachine cashMachineObj = new CashMachine(null);
    

    Better:

    CashMachine cashMachineObj = new CashMachine(new ArrayList<>());
    

    The above simply creates an empty list and passes that into the CashMashine.

    In other words: there are many ways to create lists; and you can pick whatever approach you like. Even things like:

    CashMachine cashMachineObj = new CashMachine(Arrays.asList(account1, account2));
    

    where account1, account2 would be existing Objects of the Account class.