As you can guess by now, immutability is the underlying big theme. The following Java code reverses a list in place:
List<Integer> list = Lists.newArrayList(1,2,3,4); // List<Integer> refList = Lists.newArrayList(list); // 1 List<Integer> refList = list; Collections.reverse(list); System.out.println(list); System.out.println(refList);
The problem is when we do the reversal in place, the code using the list as a reference also sees the change. To prevent this, we need to use the statement at the part labeled as
1—the defensive copy technique. The other problem with changing the list in place is thread safety. We need to carefully synchronize the list access so we stay away from heisenbugs. To know more about them, refer ...