-1

I'm trying to change the value on an ArrayList<String> called this way

mails.forEach(mail -> {
     mail = "my_new_value";
     System.out.println(mail);//here the value is correct
});

But outside the loop mails has the original value,I thought that on Java every thing is passed by a reference,what is the problem?

Turing85
  • 18,217
  • 7
  • 33
  • 58
afdrd25
  • 37
  • 4
  • 4
    "*[...] on Java every thing is passed by a reference [...]*" - Java is call-by-value. Always. – Turing85 Apr 19 '18 at 14:16
  • If you really want to replace every value in the original `ArrayList` by a single value, you could simply use `Collections.fill(yourList, "the value");` ([javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#fill(java.util.List,%20T))) – Aaron Apr 19 '18 at 14:18
  • This is exactly what you need : https://stackoverflow.com/questions/4851663/iteration-of-liststring-with-modyfing-string?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Azalkor Apr 19 '18 at 14:18

3 Answers3

4

Your code is roughly the same as:

for (String mail : mails) {
    mail = "my_new_value";
}

As you can see, you're changing the variable mail to refer to a new object (i.e., the String literal). This does not change the original String inside the list!

k_ssb
  • 6,024
  • 23
  • 47
  • "*Your code is roughly the same as [...]*" - OP's code is - in some sense - a superset of this code. – Turing85 Apr 19 '18 at 14:18
1

I would recommend looking at Java's Map transformation in the Stream API.

You could do the following:

Code

public static void main(String[] args) {
        List<String> list = Arrays.asList("hello", "world");

        list = list.stream()
                .map(value -> value.toUpperCase())
                .collect(Collectors.toList());

        System.out.println(list);
    }

Output

[HELLO, WORLD]
Garreth Golding
  • 985
  • 2
  • 11
  • 19
1

The closest to what you're trying to do here is:

mails.replaceAll(v -> "my_new_value");
Andy Turner
  • 137,514
  • 11
  • 162
  • 243