/**
     * @param args
     */
    public static void main(String[] args) {
        String str1 = "welcome";
        String str2 = new String("welcome");
        System.out.println("---" + "welcome".hashCode() );
        System.out.println("---" + str1.hashCode() + "  " + (str1 == "welcome"));
        System.out.println("---" + str2.hashCode()  + "  "+ (str2 == "welcome"));
    }

输出:
---1233099618
---1233099618  true
---1233099618  false
解释:
str1 是直接指向了字符串常量池中的"welcome".
new String("welcome") 创建了新对象,并且给str2对象做了初始化。
所以以上代码有两个对象
String 重写了hashCode()方法,所以str1和str2不是同一个对象,但hashCode相同.

 

相关文章:

  • 2021-10-31
  • 2021-07-21
  • 2021-11-07
  • 2022-12-23
  • 2021-11-30
  • 2021-08-30
  • 2022-02-16
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-20
  • 2021-10-14
  • 2021-11-24
  • 2021-07-09
  • 2022-01-09
  • 2022-12-23
相关资源
相似解决方案