I have a Long variable say,
private Long m_prevPacketRecvdTime = null;
now I have a setter/getter pair for it,
public void setM_prevPacketRecvdTime() {
if (this.m_prevPacketRecvdTime == null) {
this.m_prevPacketRecvdTime = new Long(System.currentTimeMillis());
} else {
// Why to create a new Object every time
//Why I can't just set the new value
//Why use new operator here instead of an Assignment or set method call
}
}
Instead of traditional setter method I thought to improve it, by 1. passing long instead of Long, 2. Creating a new Long only once and rest of the time just setting the new value to existing Long object. But to my disbelief there is no such method in Long.
Do we really need to create a new Long object every time we want to change its value, How can we set a new long value to existing Long object (just opposite of longvalue()) ?
More Info
While Searching for the answer I also came across AtomicLong, which has similar functionalities, But I am not sure whether that can be useful for me or not. Because they clearly say AtomicLong “cannot be used as a replacement for a Long.“
You cannot, and it’s deliberate. Immutable objects have many advantages — thread safety, ease of use, security and predictability among other things. See Effective Java item 15 for additional reasons, but the wrapper classes in Java are all immutable.
That said, you should use
Long.valueOf(long)(or autoboxing) instead ofnew Long, becauseLong.valueOfknows to cache commonly used values.Allocation is relatively cheap in Java. Don’t worry too much about it. If you can produce hard numbers to prove that switching to your own custom mutable wrapper type is worth the additional code complexity, then do that, but the traditional immutable wrappers are perfectly serviceable.