迭代器创建一个新对象或修改旧对象

时间:2014-03-31 09:03:01

标签: java

只是一个java大师的问题。如果我有如下代码

public void setSeenAttribute(String notificationId , String userId){
        UserNotification userNotification = notificationRepository.getUserNotification(userId);
        if (userNotification != null) {
            for (Notification notification : userNotification.getNotifications()) {
                if (StringUtils.equals(notification.getNotificationId(), notificationId)) {
                    notification.setSeen(true);
                }
            }
            notificationRepository.createUpdateNotification(userNotification);
        }
    }

我想知道天气notification.setSeen(true);会改变原来的收藏品,还是做这样的事情毫无价值?或者什么是最好的做法?

3 个答案:

答案 0 :(得分:1)

在Java中 - "对象的引用按值"传递。因此,除非您明确重置引用以指向另一个对象,否则将修改当前对象。

答案 1 :(得分:0)

首先,这不是迭代器,您正在使用每个循环来迭代集合。 在为每个循环使用时更新值是完全正常的。这完全不允许在" Iterator"在Java中,因为它们称为Fail-fast。

所以,

notification.setSeen(true);

正在更新集合中的Object作为新引用,即。通知指向驻留在集合中的对象。

答案 2 :(得分:0)

是的,您可以执行类似的操作,因为句柄作为值传递,但它的引用是按对象进行的。为了证明这一点,这是一个小例子:

public class ModifyElementsOfCollection {

    public static void main(String[] args) {
        Collection<Wrapper<Integer>> collection = new ArrayList<Wrapper<Integer>>();

        for(int i=0; i<10; i++) {
            collection.add(new Wrapper<Integer>(i));
        }

        collection.stream().map(w -> w.element).forEach(System.out::println);

        for(Wrapper<Integer> wrapper : collection) {
            wrapper.element += 1;
        }

        collection.stream().map(w -> w.element).forEach(System.out::println);

    }

    private static class Wrapper<T> {
        private T element;

        private Wrapper(T element) {
            this.element = element;
        }
    }

}

在第二个for循环之前,输出是数字0到9,之后它们是1到10.这也适用于更复杂的东西。

顺便说一下,这个例子使用Java 8中的一些功能来打印结果,当然你也可以使用for循环。

相关问题