Search code examples
javaclassarraylistprivate-members

how should i add an object to a private static ArrayList?


i have Bank class, with a private static ArrayList that stores all the banks. how can i add every new bank created to it? i'm not allowed to create any new methods or fields, or change any of the method or constructor parameters.

this is my Bank class:

    public class Bank {
        private static ArrayList<Bank> allBanks=new ArrayList<Bank>();
        private String name;

        public Bank(String name) {
             this.name = name;
        }
    public String getName() {
            return name;
        }

and this is my Main class:

    public class Main {
        public static void main(String[] args) {
             new Bank("randomBankName");
            }
    }

Solution

  • Do it in constructor:

        public Bank(String name) {
             this.name = name;
             allBanks.add(this);
        }
    

    WARNING never do it in real project.