mercredi 30 janvier 2019

Java prototype clone is not working as expected?

public abstract class SwimmersPrototype implements Cloneable {
    public SwimmersPrototype clone() throws CloneNotSupportedException{
        return (SwimmersPrototype)super.clone();
    }
}

SwimmersPrototype.java

public class Swimmers extends SwimmersPrototype{
    List<Swimmer> swimmers;
    SortStrategy sortStrategy;

    public Swimmers() {
        swimmers = new ArrayList();
    }

    public List<Swimmer> sort() {
        return sortStrategy.sort(swimmers);
    }

    @Override
    public SwimmersPrototype clone() throws CloneNotSupportedException{
        SwimmersPrototype swp = (Swimmers)super.clone();
        return swp;
    }
}

Here i want to clone an object of this class, Swimmers.

public class Swim extends javax.swing.JFrame {
    Swimmers swimmers;
    Swimmers swimmersCopy;
    /**
     * Creates new form Swim
     */
    public Swim() {
        initComponents();
        swimmers = new Swimmers();
        fillSwimmers();
        fillTable(swimmers.getSwimmers());
        jTableListener();

        try {
            swimmersCopy = (Swimmers)swimmers.clone();

        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(Swim.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

After calling sort, that change swimmers list of the original class, the copy object, swimmersCopy is also changed.

Here I'm just displaying swimmers list of original object in a table, I can sort by a property on it, but whenever default sort button is clicked i want to list swimmers by the default order that they inserted before? But applying sort, changes the swimmers list of the cloned object too?

Aucun commentaire:

Enregistrer un commentaire