views:

88

answers:

1

Hello there! I already know, what a shallow copy is, but I'm not able to impliment it. Here's a short example.

public class Shallow {
String name;
int number;

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

Test the 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 I purpose, just the reference of the non primitive datatype String would be copied, so that by calling "shallowClone.name = 'Peter';" I would also change the name of "shallow". Am I right? But somehow, it just does not want to work ....

+3  A: 

Strings and ints are immutable. Revise your data structure to use a mutable structure which holds references, such as an array or collection. E.g.

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 the 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 to be quoted by doublequotes. In the future, please copypaste the actual, compileable and working code from your editor instead of typing it over or from top of head. Avoid red herrings.

BalusC
Well, ok. I think I've got it! Thank you very much :)
Vilius
You're welcome.
BalusC