1.13.2 Cloning custom object

Discussion in 'Spigot Plugin Development' started by i998979, Feb 8, 2020.

  1. So I have something like this

    - Dungeon
    - Boss

    - Boss
    - Checkpoint

    - String
    - Location
    - HashMap

    What I have here is 1 DungeonGroup (call it DungeonGrpA), 1 Dungeon (call it DungeonA), 1 Boss (call it BossA)
    And I am going to create a new Dungeon (call it DungeonB), and it has a copy of DungeonGrpA's Boss

    What I want is, DungeonB has DungeonGrpA's boss (string, B's location, B's hashmap) when I was creating it and DungeonA has DungeonGrpA's boss (string, A's location, A's hashmap)
    So what I should do is probably let Boss implements Cloneable and override clone(), then do whatever I want.
    The problem is, ALL Bosses are changed when one of them was modified, for example, DungeonB's hashmap was modified and DungeonA's hashmap was modified too which I didn't mean to do that.

    Did I make something wrong with cloning? Or I used the wrong type of cloning method?

    So if you are interested this is how my clone method looks like, this is "Shallow Clone" I think, maybe I need to do "Deep Clone"?
    Code (Java):

        public Boss clone() {
            try {
                return (Boss) super.clone();
            } catch (CloneNotSupportedException e) {
            return null;
  2. Ah, cloning is generally not liked by java developers because of the many lacks it has. I would suggest you make a function called copy() that looks something like this:
    Code (Java):
    public Boss copy() {
        Boss boss = new Boss();
        boss.hashMap = this.hashMap.clone();
  3. Or a copy constructor
  4. So does it look like a deep clone?
    Coz my code doesnt really allow me to do that, otherwise it would be complicated.
    And if I am not following the tricks above, does deep clone is the 2nd best suitable option?