2014-03-31 80 views
0

只是一個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);會使原來的集合中的變化,或者是毫無價值做這樣的事情?或者什麼是最佳做法?

+0

yes當您更新Notificaton的參考時,原始集合將被修改。 –

+0

如果我正確理解,我可以這樣說:「Java通過引用操作對象,所有對象變量都是引用,但是Java不通過引用傳遞方法參數;它通過值傳遞它們。 –

+0

@SaurabhKumar - 是的..你可以說 – TheLostMind

回答

1

在Java中 - 「對象的引用是按值傳遞的」。因此,除非您明確重置參考以指向另一個對象,否則會修改當前對象。

0

首先,這不是一個迭代器,您正在使用每個循環遍歷一個集合。 在使用每個循環時更新值是完全正確的。 Java中的「Iterator」完全不允許這樣做,因爲它們調用Fail-fast。

所以,

notification.setSeen(true); 

正在更新其是否有在集合作爲新的參考,即對象。通知指向駐留在集合本身中的對象。

+0

它在內部使用了一個'Iterator'。這被稱爲*增強for循環*。 –

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

相關問題