How can I swap the contents of two Integer wrappers?
void swap(Integer a,Integer b){
/*We can't use this as it will not reflect in calling program,and i know why
Integer c = a;
a= b;
b = c;
*/
//how can i swap them ? Does Integer has some setValue kind of method?
//if yes
int c = a;
a.setValue(b);
b.setValue(c);
}
You can’t, precisely because
Integeris immutable (along with the other primitive wrapper types). If you had a mutable wrapper class, it would be fine:However, due to the lack of the equivalent of
setValueinInteger, there’s basically no way of doing what you’re asking. That’s a good thing. It means that for most cases, where we may want to pass anIntegervalue to another method, we don’t need to worry about whether the method will mutate it. Immutability makes it much easier to reason about your code, without having to carefully trace what every method does, just in case it changes your data under your feet.