Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

java - String intern() behaviour

From the javaDocs of String class's intern method :

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

Consider the following use-cases:

    String first = "Hello";
    String second = "Hello";

    System.out.println(first == second);

    String third = new String("Hello");
    String fourth = new String("Hello");

    System.out.println(third == fourth);

    System.out.println(third == fourth.intern());
    System.out.println(third.intern() == fourth);
    System.out.println(third == fourth);

    System.out.println(third.intern() == fourth.intern());
    System.out.println(third.intern() == first);

    String fifth = new String(new char[]{'H','e','l', 'l', 'o'});
    String sixth = new String(new char[]{'H','e','l', 'l', 'o'});

    System.out.println(fifth == fifth.intern());
    System.out.println(sixth == sixth.intern());

    String seven = new String(new char[]{'H','e','l', 'l', 'o' , '2'});
    String eight = new String(new char[]{'H','e','l', 'l', 'o' , '2'});

    System.out.println(seven == seven.intern());
    System.out.println(eight == eight.intern());

Can someone please explain why seven == seven.intern() is true whereas the following are false:

  • System.out.println(fifth == fifth.intern());
  • System.out.println(sixth == sixth.intern());
  • System.out.println(eight == eight.intern());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

seven is the first time you use the string 'hello2'. Therefor what the intern does is insert your string to the pool (and also return it). there for it is equal to your seven.

when you work with eight, the string is already in the pool (by running seven.intern() before, therefor when you do eight == eight.intern() you will get on the left side of the equation the newly created eight string, and on the right side the string created by seven from the pool, which are not the same


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...