Home > Java > Javagetting Started > body text

Java implements copying list

王林
Release: 2020-09-11 15:51:15
forward
2060 people have browsed it

Java implements copying list

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;
}
}
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!