简体   繁体   English

如何使用自己的类克隆基于对象的数组列表?

[英]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?我有一个名为StockArrayList的类,它基本上包含添加、删除和更新方法,我正在从文本文件加载数组列表,数组列表加载到数组中,但是在加载数组列表时,它打破了除添加之外的所有方法,如果它没有加载到数组列表中 我所有的方法都按预期工作 我如何加载StockArrayList而不破坏我的方法?

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.您正在分配对 Stock 的引用,该引用可能稍后会被 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你应该实现一个复制构造函数,重写并使用clone (必须实现Cloneable接口)方法,或者将stock的成员变量Cloneable复制到Stock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM