Are String Arrays mutable?

回眸只為那壹抹淺笑 提交于 2019-12-05 04:33:15
Luiggi Mendoza

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?

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.

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.

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