Difference between creating or reusing an object reference in java

Sorry, but I couldn’t think of anything better. Could you help me understand the difference between these two scenarios.

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.

+4
source share
2 answers

You should try to keep the variables in their narrowest scope. In this case, the second case looks better than case 1. The only advantage for case 1 would be if you really need to know which last item has been added to yours Vector(which in this case seems really strange).

+6
source

, , , .

temp final .

. . Temp temp = null; .

0

Source: https://habr.com/ru/post/1539295/


All Articles