Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an Object to Vector loses Reference using Java?

I have a Vector that holds a number of objects. My code uses a loop to add objects to the Vector depending on certain conditions. My question is, when I add the object to the Vector, is the original object reference added to the vector or does the Vector make a new instance of the object and adds that?

For example, in the following code:

private Vector numbersToCalculate;
StringBuffer temp = new StringBuffer();

while(currentBuffer.length() > i) {
    //Some other code
    numbersToCalculate.add(temp);
    temp.setLength(0); //resets the temp StringBuffer
}

What I'm doing is adding the "temp" StringBuffer to the numbersToCalculate Vector. Should I be creating a new StringBuffer within the loop and adding that or will this code work? Thanks for the help!

Eric

like image 483
ericso Avatar asked Dec 02 '25 11:12

ericso


2 Answers

You need to create a new StringBuffer each time. Each item item in the Vector is just a pointer to the same StringBuffer object, so each time through the loop you are resetting the single instance of stringbuffer and adding the same reference to the Vector.

Just replace the temp.setLength(0); with temp = new StringBuffer();

like image 129
DaveJohnston Avatar answered Dec 04 '25 23:12

DaveJohnston


If you have to have an independent object added to the Vector, create a new one each time.

You're adding references to the vector. If the state of an object changes, then all references to it see the change.

like image 35
duffymo Avatar answered Dec 04 '25 23:12

duffymo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!