Why don't arrays refer to the same object as strings?

A String reference to the same object if you declare them without using the “new” keyword as follows:

String s1 = "Some string";
String s2 = "Some string";

System.out.println(s1 == s2); 
//prints true because 
//they reference to the same object

However, contrary to what I expected from this with an array, it does not work:

char[] anArray = {'A', 'r', 'r', 'a', 'y'};
char[] oneArray = {'A', 'r', 'r', 'a', 'y'};
System.out.println("anArray == oneArray : " + (anArray == oneArray));
//prints false

We didn’t explicitly mention that they are “new” arrays, so why don’t they refer to the same object on the heap?

+4
source share
4 answers

Because arrays, unlike strings, are mutable. Usually you do not want to change the object referenced by one variable to an supposedly independent object referenced by another variable.

char[] firstArray = {'A', 'r', 'r', 'a', 'y'};
char[] secondArray = {'A', 'r', 'r', 'a', 'y'};

firstArray[0] = 'X';
firstArray[1] = '-';

System.out.println(firstArray);
System.out.println(secondArray);

, "" (.. ):

X-ray
X-ray

: :

X-ray
Array
+8

, "" , ?

: ? , JVM. ; , ( ), JVM .

, , : s1 s2 ?

: - , JDK JVM . Java , , , :

s1 s2 , # 3. ( ):

String s1 = "Some string";
int a = 1;
String s2 = (a == 1 ? "Some" : "Foo") + " string";
System.out.println("Same? " + (s1 == s2));
System.out.println("Equivalent? " + s1.equals(s2));

:

Same? false
Equivalent? true

, s2, intern ed, string.

, intern . , Java .

+4

System.out.println(s1 == s2); true , String, ( ) . .

:

String s1 = new String("Some string");
String s2 = new String("Some string");

false System.out.println(s1 == s2);.

+3

Strings in java are stored in a string table. When you create two identical lines, they will refer to the same object. If you want to find out if the string value matches the other, you will have to do String.Equals ().

Since arrays are not stored in the array table, they will refer to different objects. if you want to know if the contents of the two arrays are the same, you have to iterate through the arrays using String.Equals ().

+1
source

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


All Articles