Ashish
Ashish

Reputation: 14707

Difference between creating or reusing the object reference in java

I am sorry but I could not think any better title for the question. Could you please help me understand the difference between these two scenario.

public class Temp {
int value;

public Temp(int i) {
    this.value = i;
}

public void method(Vector<Temp> vec) {
    Temp temp=null;

    // first case, creating new object but reusing the reference
    for (int i = 0; i < 10; i++) {
        temp = new Temp(i);
        vec.add(temp);
    }

    // second case, object and reference are new
    for (int i = 0; i < 10; i++) {
        Temp temp1 = new Temp(i);
        vec.add(temp1);
    }

}
}

Which implementation should be best practice to follow.

Upvotes: 4

Views: 650

Answers (2)

Braj
Braj

Reputation: 46841

I prefer second option than first one to make sure that it's always initialized at the time of declaration.

You can't declare temp as final in first option.

Note : Do not leave local variable uninitialized. It should be Temp temp = null; in first option.

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You should try to maintain the variables in their narrowest scope. In this case, second case seems better than case 1. The only benefit for case 1 would be if you really need to know which was the last element added to your Vector (which in this case seems to be really odd).

Upvotes: 6

Related Questions