Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, is this a Deep copy?

Tags:

java

deep-copy

I cant seem to get a clear precise answer by reading any of the similar questions, I'm trying to deep Clone an object in Java using a copy constructor is this a deep copy:

public class Tile{
    Image sprite = null;
    int x = 0;
    int y = 0;
    public Tile(Image setImage, int sX, int sY){
         this.sprite = setImage;
         this.x = sX;
         this.y = sY;
    }
    public Tile(Tile copyTile){
         this.sprite = copyTile.sprite;
         this.x = copyTile.x;
         this.y = copyTile.y;
    }
    public void setNewLocation(int sX, int sY){
         this.x = sX;
         this.y = sY;
    }
}

Then when I create my tile map I could do something like this

List<Tile> tileList = new List<Tile>();
Tile masterGrassTile = new Tile(grassImage, 0,0);
tileList.set(0,new Tile(masterGrassTile));
tileList.set(1,new Tile(masterGrassTile));
tileList.get(0).setNewLocation(0,32);
tileList.get(1).setNewLocation(0,64);

If i were to render both tiles at their respective locations would that work? or was the assignment tileList.get(1).setNewLocation(0,64); effecting like a reference and all of them have the same location as the last assignment.

like image 264
Snowdrama Avatar asked Mar 25 '13 08:03

Snowdrama


People also ask

Is Java deep copy or shallow copy?

Shallow copy is preferred if an object has only primitive fields. Deep copy is preferred if an object has references to other objects as fields. Shallow copy is fast and also less expensive. Deep copy is slow and very expensive.

What is a deep copy Java?

Deep copy/ cloning is the process of creating exactly the independent duplicate objects in the heap memory and manually assigning the values of the second object where values are supposed to be copied is called deep cloning.

Is clone method a deep copy Java?

The default implementation of Java Object clone() method is using shallow copy. It's using reflection API to create the copy of the instance.


1 Answers

is this a deep copy ?

No, it's not because this.sprite = copyTile.sprite; both objects of Tile is refering to same object of Image.

If i were to render both tiles at their respective locations would that work? or was the assignment tileList.get(1).setNewLocation(0,64); effecting like a reference and all of them have the same location as the last assignment.

No, the values of x and y are independent in the two objects of Tiles and code should work and both the objects will have different x and y values.

like image 58
Subir Kumar Sao Avatar answered Sep 22 '22 00:09

Subir Kumar Sao