The trick is that the contents of the array are not what is passed to the method. The contents of the array can be read and written, but writing one changes the original. Java does not create a new copy for you unless you use it yourself. This means that you can transfer information back just by using the picture in what was transmitted to you. This is great as long as you document the behavior, so someone using this method is not surprised when their data is goodbye.
public static void main(String[] args) { int[] a = {0, 1}; int[] b = {2, 3}; int[] c = new int[a.length + b.length]; concatArray(a, b, c); for (int i : c) { System.out.println(i); } } public static void concatArray(int[] prefix, int[] suffix, int[] result) { int prefixLength = prefix.length; int suffixLength = suffix.length; if( result.length < prefixLength + suffixLength) { throw new IllegalArgumentException(); } for (int i = 0; i< prefixLength; i++) { result[i] = prefix[i]; } for (int i = 0; i< prefixLength; i++) { result[i+prefixLength] = suffix[i]; } }
exit:
0 1 2 3
The same trick works with objects until they are immutable. If someone hands you a bean, you can play setters with him, and if you shouldn't, cause all kinds of chaos.
This is why setting the identifier of an array or object as final does not guarantee immutability. Any user can still call configuration methods (if they exist on the object) or create new assignments in the array. All final ones are handcuffs for an object or an array for an identifier. He does not block the portfolio. Getting rid of setters blocks the portfolio.
What we call immutable. Lines are unchanged and therefore this trick will not work with Strings.
When you go to the method as if you made the final identifier. You cannot modify an array or object without the calling context losing information about what you are playing with. If you stick to the same array or object, you can play with it as much as it is allowed, and the call context will see everything that you have done.
Infact, whenever you return anything other than a primitive, what you really return is a new place and says, "Look what I did here." This trick works simply by sticking to previously known places.
source share