zoukankan      html  css  js  c++  java
  • java string ==和equals的使用

     1 package com.example.base.string;
     2 
     3 public class MyStringTest {
     4 
     5     public static void main(String args[]) {
     6         testString();
     7     }
     8     
     9     private static void testString() {
    10         String hello = "Hello";
    11         String hello2 = new String("Hello");
    12         String lo = "lo";
    13         //false. ==比较的是引用.hello是一个字符串常量表达式,并实现为调用interned,以共享不同的示例(string pool)
    14         //hello2是一个对象,指向的是堆上的一个地址
    15         System.out.println(hello == hello2);            //false
    16         //true. equals比较的是两个对象的值
    17         System.out.println(hello.equals(hello2));       //true
    18         //true. intern()会检查当前字符串池是否包含这个字符串。包含则返回池中的字符串,否则将字符串对象添加到池中,并返回该字符串对象的引用
    19         //(最终结果就是返回一个指向常量池字符串的引用)
    20         System.out.println(hello == hello2.intern());   //true
    21         //true. 两个都是常量表达式(编译时确定的),都是指向字符串池的引用
    22         System.out.println(hello == "Hello");           //true
    23         //true. 不同类下的两个常量表达式,依然是指向同一个字符串池的引用
    24         System.out.println(Other.hello == hello);       //true
    25         //true. 不同包下的两个常量表达式,依然是指向同一个字符串池的引用
    26         //System.out.println(com.example.base.string.other.Other.hello == hello);     //true
    27         //true. 两个都是常量表达式,都是指向字符串池的引用
    28         System.out.println(hello == ("Hel" + "lo"));    //true
    29         //false.  后者不是常量表达式,是运行时通过串联计算的字符串(lo是一个对象,不是常亮"xxx"),会新建对象
    30         System.out.println(hello == ("Hel" + lo));      //false
    31         //true. 将新对象intern()会返回指向字符串池的引用
    32         System.out.println(hello == ("Hel" + lo).intern());     //true
    33     }
    34 }
    35 class Other {
    36     static String hello = "Hello";
    37 }
  • 相关阅读:
    LeetCode 297. 二叉树的序列化与反序列化
    LeetCode 14. 最长公共前缀
    LeetCode 1300. 转变数组后最接近目标值的数组和
    bigo一面凉经
    LeetCode 128.最长连续序列
    LeetCode中二分查找算法的变种
    LeetCode 93. 复原IP地址
    LeetCode 1004. 最大连续1的个数 III
    LeetCode 1282. 用户分组
    多线程理解
  • 原文地址:https://www.cnblogs.com/gc65/p/java.html
Copyright © 2011-2022 走看看