Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

java - How do I load an ArrayList that I can acces and manipulate from other classes without loading them more than once?

Lets say I have a class called Product which contains a counstructor like this

public Product(String name, double price, int barcode){
        this.name = name;
        this.barcode = barcode;
        this.price = price;
    }

I then have another class ImportData which have a method that load a lot of products into a List that returns a productList.

I now want to acces this list from different classes without have to load the data into the csv-file once again. So instead of this:

ImportFruitAndVegatables iFV = new ImportFruitAndVegatables();
List<Product> products = iFV.fillListWithProducts();

I want something like this

mainController.products

Because my mainController already runs the method. Like this

List <Product> productList = importFruitAndVegatables.fillListWithProducts();

So my question is: Are there any way you only need to run this method once and dont need to run it again? Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can share a reference to an object in at least these ways:

  • Global variable. In Java that is a static variable defined on a class. Mark as final if the object reference should be assigned only once during your app’s execution.
  • Singleton design pattern. In Java, that is best done as an enum defining a single object named something like INSTANCE.
  • Public instance variable. If List <Product> productList is a member field on your instance of mainController, then marking that field as public allows any other code to call mainController.productList.
  • Pass the list as an argument to a method. For example, defining a method such as public SalesReport produceSalesReport( List <Product> productList ) {…}.
  • A method that returns the object reference. This offers the opportunity for lazy-loading when the desired object is not instantiated until the first call to this method.

You do not provide enough detail to make a recommendation. Generally best to use a method that returns a list.

Tip: Generally best to provide either a copy of the list or a non-modifiable list so the calling programmer cannot disturb the original list. See List.copyOf.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...