问题
I wonder if String arrays in Java are mutable ? I know that Strings are immutable, but how about string Arrays ?
If I have a string array, and change the content, will a new string object be created ? Or will the actual value just be changed ?
Thanks in advance
回答1:
The String
s contained in the String[]
are indeed immutable, but the array is mutable.
This is well explained in this answer:
- Immutability means that objects of a certain type can not change in any meaningful way to outside observers
Integer
,String
, etc are immutable- Generally all value types should be
- Array objects are mutable
- It may be an array of references to immutable types, but the array itself is mutable
- Meaning you can set those references to anything you want
- Also true for array of primitives
- An immutable array will not be practical
- References to objects can be shared
- If the object is mutable, mutation will be seen through all these references
EDIT:
Somewhat related: Why can't strings be mutable in Java and .NET?
回答2:
As far as i remember the field in your array will reference another String
String[] array {"I","like","rain"};
array[2] = "sun"
your array can be changed. the Strings themselves not.
回答3:
In Arrays, each element is just a pointer to an object. So, when you do something like
String one = "1";
String two = "2";
String three = "3";
String four = "4";
String[] myStringArray = {one, two, three};
myStringArray[2] = four;
Then the pointer that was at the 3rd element of the array now points to the four instead of three.
来源:https://stackoverflow.com/questions/16125616/are-string-arrays-mutable