Cloning an Integer

rubixibuc picture rubixibuc · Apr 28, 2011 · Viewed 28.5k times · Source

I am trying to clone a object of class Integer, which does implement the cloneable inteface.

Integer a = new Integer(4);  
Integer b = a.clone();

I know there are work arounds for this, but I must implement it like this. why I am getting this error = clone() has protected access in java.lang.Object

Why would it say this? Isn't the clone method a public abstract method of clonable interface, what does it have to do with object. Thanks in advance :-)

Answer

rlibby picture rlibby · Apr 28, 2011

java.lang.Integers are immutable. There is no reason to clone one. If you're trying to waste memory, try Integer.valueOf(myInteger.intValue()).