for循环外定义对象(变量)和for循环里定义对象(变量)的区别
作者:互联网
外边:
package com.sky.demo; import java.util.ArrayList; public class Test { public static void main(String[] args) { User user = new User(); ArrayList<User> list = new ArrayList<User>(); for (int i = 0; i < 3; i++) { user.setId("a"+i); user.setName("丫丫"+i); user.setHobby("篮球"+i); list.add(user); } for (User user1 : list) { System.out.println(user1); } } }
User{id='a2', name='丫丫2', hobby='篮球2'}
User{id='a2', name='丫丫2', hobby='篮球2'}
User{id='a2', name='丫丫2', hobby='篮球2'}
里面:
package com.sky.demo; import java.util.ArrayList; public class Test { public static void main(String[] args) { ArrayList<User> list = new ArrayList<User>(); for (int i = 0; i < 3; i++) { User user = new User(); user.setId("a"+i); user.setName("丫丫"+i); user.setHobby("篮球"+i); list.add(user); } for (User user1 : list) { System.out.println(user1); } } }
User{id='a0', name='丫丫0', hobby='篮球0'}
User{id='a1', name='丫丫1', hobby='篮球1'}
User{id='a2', name='丫丫2', hobby='篮球2'}
标签:变量,丫丫,篮球,定义,循环,User,hobby,id,user 来源: https://www.cnblogs.com/dongyaotou/p/16553617.html