簡體   English   中英

迭代器創建一個新對象或修改舊對象

[英]Iterator creates a new object or modifies the old one

對於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); 會改變原始系列,還是做這樣的事情毫無價值? 或什么是最佳做法?

在Java中-“對對象的引用按值傳遞”。 因此,除非您明確地將引用重置為指向另一個對象,否則將修改當前對象。

首先,這不是一個迭代器,您正在使用每個循環來迭代集合。 並且在每次循環使用時更新值都非常好。 Java中的“迭代器”根本不允許這樣做,因為它們被稱為“快速失敗”。

所以,

notification.setSeen(true);

正在更新集合中存在的對象作為新引用,即。 通知指向駐留在集合本身中的對象。

是的,您可以執行類似的操作,因為句柄是作為值傳遞的,但其引用是按對象傳遞的。 為了證明這一點,這是一個小例子:

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循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM