Assigning new value to Long instance

S

sven

Hi,

in my program I have two objects pointing to a common Long instance. I
want both of them being able to alter the value of the Long instance.
However, a setValue function or something similiar does not seem to be
part of the Long class. Is there any way to change the value of this
long without changing the object reference (rather than wrapping the
Long class and implementing a setter function)?

Any ideas?
 
B

Boris Stumm

sven said:
Hi,

in my program I have two objects pointing to a common Long instance. I
want both of them being able to alter the value of the Long instance.
However, a setValue function or something similiar does not seem to be
part of the Long class. Is there any way to change the value of this
long without changing the object reference (rather than wrapping the
Long class and implementing a setter function)?

Any ideas?

Longs are immutable. Maybe try java.util.concurrent.atomic.AtomicLong,
will save you the trouble of having to implement an own wrapper.
 
S

sven

Longs are immutable. Maybe try java.util.concurrent.atomic.AtomicLong,
will save you the trouble of having to implement an own wrapper.

Thanks, that saves a lot of hassle.
 
D

Daniel Pitts

Thanks, that saves a lot of hassle.

Keep in mind that AtomicLong has extra functionality to deal with
thread-safety. If you know you don't need thread safety, I would
suggest writing your own wrapper.

More specically, I'm assuming your "long" value actually has a
semantic meaning. For instance, numberOfSheep.

public class SheepCounter {
private long numberOfSheep;
public Long getNumberOfSheep() {
return numberOfSheep;
}
public void count() {
numberOfSheep++;
}
public void setNumberOfSheep(long numberOfSheep) {
this.numberOfSheep = numberOfSheep;
}
}

Avoid primative obsession where it makes sense. You might find that
the class can start taking on more behavior, and you'll end up with
better design.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top