What does “safe” mean in the Collections.toArray () JavaDoc application?

When I read the Java source code that I found in the collection interface, it will be safe

The returned array will be "safe" because references to it are not supported. (In other words, this method should allocate a new array, even if this collection is supported by the array). Thus, the caller is free to modify the returned array.

I do not understand the point, can you give an example for me?

+4
source share
1 answer

Sure:

List<String> list = Arrays.asList("foo", "bar", "baz"); String[] array = list.toArray(new String[0]); array[0] = "qux"; System.out.println(list.get(0)); // still "foo" 
+14
source

Source: https://habr.com/ru/post/1500745/


All Articles