This post will discuss how to implement a mutable int class in Java, which is a mutable wrapper over primitive int. We will also take a look at MutableInt class provided by Apache Commons Library.

A mutable class in Java is a class whose instances can be modified after they are created. It means that the state of the object can change through various methods and operations during its lifetime. A MutableInt class is a class that wraps a primitive int value and allows it to be changed. We can either implement a custom mutable int class in Java, or use the implementation provided by the several third-party libraries.

1. Custom Implementation

We can create our own mutable int class by defining a private int value and providing public methods to access and modify it. We can also override the toString() method to return the corresponding string value of the int field. By implementing our own custom solution instead of relying on third-party libraries, we can reduce the number of external dependencies in our app and have more flexibility to add more methods as needed. Here is an example of how the custom MutableInt class might look like in Java:

Download  Run Code

2. Using Apache Commons Lang

The Apache Commons Lang library provides an implementation of the MutableInt class, which has similar methods as the custom implementation, as well as some additional methods such as intValue(), toInteger(), doubleValue(), equals(), hashCode(), and compareTo(). The basic usage of this class is demonstrated below:

Download Code

 
Note that Guava library provides an implementation of the AtomicInteger class, which is a thread-safe mutable int that supports atomic operations. It has similar methods as the Apache Commons Lang MutableInt class, as well as some additional methods such as getAndIncrement(), incrementAndGet(), getAndDecrement(), decrementAndGet(), getAndAdd(), addAndGet(), compareAndSet(), and getAndUpdate().

That’s all about implementing a mutable int class in Java.