简体   繁体   中英

How do I clone a object based arraylist with its own class?

I have a Class called StockArrayList which basically holds add, delete and update methods, I am loading a array list from a text file the array list loads into the array however in loading the array list it breaks all my methods apart from add, if it isn't loaded into array list all my methods work as expected how do i load the StockArrayList without breaking my methods?

public class StockListCLI {
Scanner in = new Scanner(System.in);
StockArrayList Stock = new StockArrayList();;
/**
 * takes a existing stockListand uses it though out the class
 * @param stock 
 */
public StockListCLI(StockArrayList stock){
    //Stock = (StockArrayList) stock; //uncomment to load stock data but it will break most of the functions below
}

You are assigning a reference to Stock, that probably later will be collected by the GC. You should implement a copy constructor, override and use the clone (must implement Cloneable interface) method, or copy 1 by 1 the member variables of stock to Stock

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