Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't the wrapper classes for Primitives have a setter?

What is the reason why Wrapper classes (like Integer, Double, etc.) don't have a setter for their inner primitive value ?

I am asking this because that kind of functionality would have simplified calculus, and have made the Java language a little more flexible .

Let me give you some examples.

1) Let's take the following example:

Integer x = new Integer(5);
x++;

The previous code behind the scenes is performing autoboxing . Something like:

int x_tmp = x.intValue();
x_tmp++;
x = new Integer(x_tmp); // Yes that's a new memory allocation

Because of this problem doing calculus on Wrapper is slower than performing on plain primitive types. With a setter it would've been more easy to increment the inner value, without allocating another object on the heap.

2) Another issue that is bugging me is that is impossible in Java to write a swap function like I can do in C (using pointers) or in C++ (pointers or references).

If i write void swap(Integer x, Integer y) I cannot acces the inner value because, and It is going to be impossible for me to swap the values.

PS: A friend of mine suggested that i should consider the bigger picture, and think in terms of concurrency and type immutability.

So do you have an explanation for this ? Thanks!

like image 639
Andrei Ciobanu Avatar asked Dec 08 '22 02:12

Andrei Ciobanu


1 Answers

Wrapper classes are usually not used unless you need to put them into a collection. If they were mutable it would make problems if used inside sets and as keys for hashtables.

Sets and hashtables need the hash value to be always the same.

like image 112
Christian Avatar answered Jan 05 '23 17:01

Christian