Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have mutable types for Integer, Float, Double, Long?

I am in a situation where I want to use mutable versions of things like Integer. Do I have to use these classes (below) or does Java have something built in?

http://www.java2s.com/Code/Java/Data-Type/Amutableintwrapper.htm

like image 258
smuggledPancakes Avatar asked Dec 23 '10 15:12

smuggledPancakes


People also ask

Is Integer in Java mutable?

A: The answer to your question is simple: once an Integer instance is created, you cannot change its value. The Integer String , Float , Double , Byte , Long , Short , Boolean , and Character classes are all examples of an immutable class.

Is float mutable in Java?

It is because all primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.

Are doubles mutable in Java?

For example, In Java, String, Integer, Double are Immutable classes, while StringBuilder, Stack, and Java array are Mutable.

What is a mutable Integer?

Simple put, a mutable object can be changed after it is created, and an immutable object can't. Objects of built-in types like (int, float, bool, str, tuple, unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable.


2 Answers

You could always wrap the value in an array like int[] mutable = {1}; if including the code for a mutable wrapper class is too cumbersome.

like image 149
Alex Jasmin Avatar answered Oct 13 '22 00:10

Alex Jasmin


Since JDK 1.5 java now has java.util.concurrent.atomic.AtomicInteger

This is a thread safe mutable integer, example of use:

final AtomicInteger value = new AtomicInteger(0); 

then later on:

value.incrementAndGet(); 
like image 43
Clive Avatar answered Oct 13 '22 00:10

Clive