String intern()行为 [英] String intern() behaviour

查看:108
本文介绍了String intern()行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 javaDocs String类的实习方法:

From the javaDocs of String class's intern method :


当调用intern方法时,如果池已包含等于此的
字符串由equals(Object)
方法确定的String对象,然后返回池中的字符串。否则,将
String对象添加到池中,并返回对此String
对象的引用。

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.

考虑以下用例:

    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());

有人可以解释为什么 seven == seven.intern( ) true ,而以下是 false

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


  • System.out.println(Fifth == fifth.intern());

  • System.out.println(six == six.intern());

  • System.out.println(8 = = eight.intern());

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

推荐答案

七是第一次使用字符串'hello2'。因此实习生所做的是将你的字符串插入池中(并返回它)。因为它等于你的七。

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.

当你使用8时,字符串已经在池中(通过运行 seven.intern( )之前,当你做 8 == eight.intern()时,你将在等式的左边得到新创建的八个字符串,右侧是由池中七个创建的字符串,它们不相同

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

这篇关于String intern()行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆