Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "Safe" mean in the Collections.toArray() JavaDoc?

Tags:

java

When I read java source code, I found in the collection interface, will be safe

The returned array will be "safe" in that no references to it are Maintained by this collection.(In other words, this method must allocate a new array even if this collection is backed by an array).The caller is thus free to modify the returned array.

I do not understand the meaning, can you provide an example for me?

like image 448
yanbit Avatar asked Dec 08 '22 13:12

yanbit


1 Answers

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"
like image 56
Chris Jester-Young Avatar answered Dec 11 '22 10:12

Chris Jester-Young