search

Home  >  Q&A  >  body text

java - for循环中创建对象

下面这两种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中的内容有影响吗,还是只是性能上有区别?

迷茫迷茫2803 days ago1598

reply all(11)I'll reply

  • 迷茫

    迷茫2017-04-17 17:44:37

    There is a difference between these two, and the execution results are different
    Please refer to the following article:
    http://ocaicai.iteye.com/blog...

    reply
    0
  • Cancelreply