简体   繁体   中英

How to copy elements from temporary ArrayList into private ArrayList in newly created object?

I am writing a JavaFX program for my school project. So I have 2 classes, Product and controller class.

Inside the Product class I have an ArrayList that stores parts in each Product object created by this class. This ArrayList is private and can be only accessed by methods addAssociatedPart , deleteAssociatedParts and getAllAssociatedParts .

Inside the controller class I have temporary ArrayList that stores said parts until user hits Save button.

Upon hitting save button I would like to copy contents of temporary list into objects private ArrayList .

I tried to search online, but figured out I cannot use Collections.copy and clone methods.

Also upon hitting Save button, Controller class creates Product object from textfields filled by user.

Thank you for your time and patience!

You can use addAll inside ArrayList to add all your members to your private list;

public void addAssociatedPart(List<Product> productsToAdd) {
   this.privateProducts.addAll(productsToAdd);
}

public boolean addAll(Collection c)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty.)

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