简体   繁体   中英

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

    }
}

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.

If you read the docs for List , you will see that List is actually an interface!

Interfaces are like protocols. The methods in interfaces don't have implementations. The classes that implement the interface must provide those implementations. You can't just create a new List object by calling its constructor because it doesn't make sense to create an object with methods that have no implementations!

What you should do is to create an object of a class that implements List , for example, ArrayList .

 ArrayList<Account> accounts = new ArrayList<>();

You can now pass accounts to the constructor of CashMachine .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM