samedi 27 mai 2017

What is a best design to hold a "global" mutable list?

Let's say that I have an ArrayList of class Person and I have two objects that are generated from two different classes which read and write to this ArrayList.

For example,

public class Main { 
   public static void main(String[] args) { 
       A a = new A();
       B b = new B();
   }
}

What, in your opinion is the best design to handle this ArrayList. I can think about two options:

  1. create the Array List in class Main:

    public class Main { 
    
           public static ArrayList<Person> list = new ArrayList<>();
    
           public static void main(String[] args) { 
               A a = new A();
               B b = new B();
           }
    }
    
    

and then access the list inside classes A and B by:

Main.list....

  1. Create the ArrayList as a local variable in main method and send to the constructor of A and B.

    public class Main {

           public static void main(String[] args) {
               ArrayList<Person> list = new ArrayList<>(); 
               A a = new A(list);
               B b = new B(list);
           }
    }
    
    

Aucun commentaire:

Enregistrer un commentaire