2014-03-31 44 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循环。

相关问题