Shallow copy in Java

I already know what a shallow copy is, but I cannot implement it. Here is a brief example.

public class Shallow { String name; int number; public Shallow (Shallow s) { this.name = s.name; this.number = s.number; } } 

Check implementation ...

 public class ShallowTest { public static void main (String[] args) { Shallow shallow = new Shallow("Shallow", 123); Shallow shallowClone = new Shallow(shallow); shallowClone.name = 'Peter'; shallowClone.number = 321; System.out.println(shallow.name + " - " + shallow.number); } } 

As a goal, I would copy only a reference to the non-primitive data type String, so by calling โ€œshallowClone.name =โ€œ Peter โ€; I would also change the name toโ€œ shallow. โ€Am I right? But somehow this just doesn't work. ...

+4
source share
1 answer

Lines and ints are immutable. Revise the data structure to use a mutable structure that contains references, such as an array or collection. For instance.

 public class Shallow { private Object[] properties = new Object[2]; public Shallow(String name, int number) { this.properties[0] = name; this.properties[1] = number; } public Shallow(Shallow s) { this.properties = s.properties; } public String getName() { return (String) properties[0]; } public void setName(String name) { this.properties[0] = name; } public int getNumber() { return (Integer) properties[1]; } public void setNumber(int number) { this.properties[1] = number; } } 

And use getters / setters instead of directly accessing properties.

 Shallow shallow = new Shallow("Shallow", 123); Shallow shallowClone = new Shallow(shallow); shallowClone.setName("Peter"); shallowClone.setNumber(321); System.out.println(shallow.getName() + " - " + shallow.getNumber()); // Peter - 321 

Also note that strings are usually quoted with double quotes. In the future, please copy the actual, compiled and working code from your editor, instead of typing it on top. Avoid the red herring.

+5
source

Source: https://habr.com/ru/post/1307949/


All Articles