下面这两种for循环中新建对象写法有什么区别呢?
第一种:
list<User> users = new ArrayList<User>();
User user = null;
for (int i = 0; i < 10; i++) {
user = new User();
user.setUserId(i);
user.setUserName("segment" + i);
users.add(user);
}
……
第二种:
list<User> users = new ArrayList<User>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setUserId(i);
user.setUserName("segment" + i);
users.add(user);
}
……
这两种写法对集合users中的内容有影响吗,还是只是性能上有区别?
No impact, just the scope of the user variable is different.
If you need to do special processing on the last value of the loop, use the first form; otherwise, I think the second form is better.
A new object is created every time it loops, and each object is different. There is no difference between the two ways of writing
Everything is fine. No difference
Personally, there seems to be no difference..
Maybe the first one has better performance, but this is not a problem that Java programmers consider at all. Intuitively speaking, the second one has better coding standards and readability.
It seems that the first method creates one more object, and the rest has no effect
Remember one principle: variables should be declared and created only when needed. So: the second one, but the difference is small. Those students who say there is a difference in efficiency hope to have data to support it and show it to everyone
The content has no impact. It is the first type. After the for loop ends, the user still points to a piece of memory that will not be recycled by the garbage collector.
Basically no difference. The only difference is that the reference counter adjustment timing is slightly different, but the object is always referenced, and even the GC will not be triggered. So this one really makes no difference.
For objects declared in the loop body, marking the object will release the reference after the scope ends. However, if it is declared outside the loop, the previous reference will not be released until the next assignment. Even if it is not saved by the container, under JAVA's GC mechanism, there is not much difference. The object will not be released until the next GC trip.
Considering the readability of the code, if the object is used within the loop body, do not declare it outside. When the scope is large and the code complexity is high, it is easy to make errors.
Still the same principle: create when needed.