Are String Arrays mutable?

人走茶凉 提交于 2019-12-10 03:59:43

问题


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 Strings 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!