Java:判断字符串相等
PHPz
PHPz 2017-04-18 10:46:45
0
5
931
PHPz
PHPz

学习是最好的投资!

reply all(5)
黄舟
String a = new String("abc");
a = a.intern();

String b = "abc";

if (a == b) {
    System.out.println("相等");
} else {
    System.out.println("不等");
}

You are callinga.intern()方法,但是你又没有将返回结果重新赋值,a还是原来那个a.

左手右手慢动作

Use equals() to judge string equality. This question in Java has failed!

PHPzhong

a.intern(); will not change the reference of the a character, it has a return value.
The following will be equal

String b = a.intern();
左手右手慢动作
String a = new String("abc");

A and "abc" here are two objects. When the intern method is called, the character constant pool already contains a string equal to this object, so the intern method call is useless, even if b="abc" is followed. , b and a are not the same object.

If you want the output to be equal, either the first sentence becomes:

String a = "abc";

Or the second sentence becomes:

a = a.intern();
洪涛

The first thing you need to know is that the == operation determines whether two objects or basic types a and b point to the same memory area

The underlying implementation of String is
private final value[]
When String is instantiated, it actually divides a continuous memory to save the char array through System.arraycopy.

new String("abc") is actually not recommended for initializing String in this way. The actual implementation requires one more step than a = "abc". The underlying steps are

  1. Divide the memory space and create a temporary array temp

  2. temp[0] = 'a';temp[1] = 'b';temp[2] = 'c';

  3. Create the array value and point the memory space pointed by value to the memory space pointed by temp, that is, &value = &temp (if a = "abc" is used, this step is not required)

The intern method is a method provided by jdk1.5 and is used for memory optimization. The same String refers to the same memory space, which is actually the third step above. If a and b are equal here, it can be written as

String a = "abc";
String b = "abc".intern(); 或者String b = a.intern();

In fact, the operation performed is the third step above, that is, b = a;

String b = "abc"The actual underlying implementation is:

  1. Divide the memory space and create an array value

  2. value[0] = a.value[0];value[1] = a.value[0]';value[2] = a.value[0];

In the second step, value[0] in String a in value[0] in String b actually points to the same memory address, so in fact b.value[0] = a.value[0] = 'a', but b.value is not equal to a.value. The fundamental reason is that the memory areas pointed to are different

It is recommended to take a look at the source code analysis of String
[JAVA source code analysis - Java.lang] String source code analysis

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template