how to use arraylist [closed]

1

I have a question about the use of Arraylists, I have to do a project in which I have to store orders in an arraylist that gives me an excel file, I have the main class and the requested class, each order with its respective attributes, but my doubt is, where should I instantiate the arraylist? Should I instantiate it in the main class, for that same class to add the orders that I am getting from reading the excel (which is done in the main class)? o Should I instantiate it in the requested class, but creating a "List" interface? Helpaaaa please!

    
asked by sebastian 07.10.2016 в 23:23
source

1 answer

1
  

Where should I instantiate the arraylist?

Where you need to do it. A class can be instantiated where you need to do it, you do not have to think twice. However, this "need" will become the standard on where to instantiate certain classes. For example, when you learn about design patterns, you will see that certain classes belonging to X domain are better instantiated in Y domain.

In your case, that you are simulating a database, that list is best enclosed in a class that indicates its purpose. For example:

public class Store {

    public static final List<Product> items;

    static {
         items = new ArrayList<>();
    }

    public Product save(Product p) {
        items.add(p);
        return p;
    }

    public int count() {
        return itens.size();
    }
}

Semantically it's better than just instantiating a list:

Store store = new Store();
store.save(product);
  

Should I instantiate it in the requested class, but create a "List" interface?

You do not have to see one thing with another. Instanciar using the interface List has polymorphic objectives. Since this interface has many implementations, you can save in an List object an instance of ArrayList , LinkedList , SortedList , etc.

I recommend you to learn the theory of programming and object-oriented design well. It is much more than classes and objects and will help you understand different situations later.

    
answered by 08.10.2016 в 10:17