Background:
At first I wanted to copy a collection when entering a new page and save it for subsequent operations, so I just wrote List A=List B, later I found that when operating B, the data in A will also change accordingly.
(Video tutorial recommendation: java course)
It was found through query that directly using "=" is equivalent to an array with the same content in java pointing to the same address, that is After shallow copying, A and B point to the same address. The consequence is that changing B will also change A, because changing B means changing the content of the address pointed to by B. Since A also points to the same address, A and B are changed together. To copy an independent array, you can use the following method:
public class GoodsBean extends HttpResult implements Cloneable{ @Override protected Object clone() throws CloneNotSupportedException { GoodsBean o = null; try { o = (GoodsBean) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return o; } public ArrayList<GoodsBean> deep_clone(ArrayList<GoodsBean> cells, ArrayList<GoodsBean> clone_cells){ for(GoodsBean c : cells){ try { clone_cells.add((GoodsBean) c.clone()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } return clone_cells; } }
Related recommendations: java introductory tutorial
The above is the detailed content of Java implements copying list. For more information, please follow other related articles on the PHP Chinese website!