Java, is this a Deep copy? -


i cant seem clear precise answer reading of similar questions, i'm trying deep clone object in java using copy constructor 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 create tile map 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 render both tiles @ respective locations work? or assignment tilelist.get(1).setnewlocation(0,64); effecting reference , of them have same location last assignment.

first, lets review differences between deep , shallow copy.

a shallow copy points same references source. if make copy of instance a named b changes fields containing objects in b modify these fields in a since pointing same reference.

a deep copy has independent fields/references, not point source's references. change field/property on copy not impact source's fields/properties.

in case, believe have made shallow copy since assigning reference of sprite field source copy's sprite field.

to illustrate this, have modified tile classes source expose image , have mocked image class.

modifications proof of concept

class tile{         /* rest of class*/         //additions     public image getsprite() {         return sprite;     }     public void setsprite(image sprite) {         this.sprite = sprite;     }  }  //mock class image{     public string name;     public image(string name){         this.name = name;     } } 

proof of concept

public static void main(string[] args) {     list<tile> tilelist = new arraylist<tile>();     tile mastergrasstile = new tile(new image("grass.png"), 0,0);      tile copytile = new tile(mastergrasstile);     copytile.getsprite().name = "water.png";      system.out.println(mastergrasstile.getsprite().name); //prints water.png } 

notice how changing copied instance's sprite property affects original instances sprite property.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -