无论是foreach,还是iterator,在遍历时,修改实体对象的引用地址都是无效的
foreach:
List<User> userList = new ArrayList<>(); userList.add(new User("ming", 11)); for (User user : userList) { if ("ming".equals(user.getName())) { user = new User("ming"); user.setAge(20); } } logger.info("{}", userList); // 11:55:41.059 [main] INFO com.demo.test.JUCT - [User [age=11, name=ming]]
iterator:
List<User> userList = new ArrayList<>(); userList.add(new User("ming", 11)); Iterator<User> iterator = userList.iterator(); while (iterator.hasNext()) { User next = iterator.next(); if ("ming".equals(next.getName())) { next = new User("ming"); next.setAge(20); } } logger.info("{}", userList); // 11:36:32.918 [main] INFO com.demo.test.JUCT - [User [age=11, name=ming]]
值修改:
List<User> userList = new ArrayList<>(); userList.add(new User("ming", 11)); Iterator<User> iterator = userList.iterator(); while (iterator.hasNext()) { User next = iterator.next(); if ("ming".equals(next.getName())) { next.setAge(20); } } logger.info("{}", userList); // 11:47:55.569 [main] INFO com.demo.test.JUCT - [User [age=20, name=ming]]
其实也很容易理解,集合中保存的为引用地址,如果是直接再new User(),那这就是一个新的地址,其在集合中是不存在的,所以最后打印出来的userList中user的age还是11,但如果直接在原来的对象上执行setAge修改年龄,则可以生效,因为原对象在集合中存在引用地址,且这个地址没有变化。