• String中==的用法


    
    
    
    
     1 public class Str_test {
     2 
     3     public static void main(String[] args) {
     4 
     5         // String pool
     6         // ==比较是否是同一个引用;对于String对象的相等性用equals(),因为该方法已经被override!(Object的equals()比较就是用==判断引用是否相等)
     7         // Array没有重写Object的equals(),Arrays重写过
     8         String a = "he";
     9         String b = "llo";
    10         String c = "hello";
    11         String d = new String("hello");
    12 
    13         System.out.println(c == a + b);// false
    14         System.out.println(c == a + "llo");// false
    15         System.out.println(c == (a + b).intern());// true
    16         System.out.println(c == (a + "llo").intern());// true
    17         System.out.println(c == "he" + "llo");// true reason:c:String pool
    18         // 中建立"hello"
    19         // "he"+"llo"成为一个新String找到String
    20         // pool存在"hello",所以相等
    21         System.out.println(c == d);// false
    22 
    23         System.out.println(c == d.intern());// true 1
    24 
    25         System.out.println(d == d.intern());// false 2
    26 
    27     }
    28 
    29 }
    annotation:
    intern()的用法:
    第一个"true"就解释了第一个疑问、intern把d的内存指向为c、所以二者相等、 字符串池中应该有两个"Hello",一个是c的引用,另外一个则是d用new出来的空间, 但使用intern后其实已经指向c的内存空间了,所以才会输出"false" 在未存在c的情况下,Stirng d = new Stirng("Hello");其实应该有两个对象,一个是创建栈中字符串池的"Hello", 另外一个是对变量"d"的指向,存在于堆内存中。用new关键字不管池中有没有都会开辟一块内存空间,只有String pool没有创建某个字符串常量时,才在池中创建该地址

     
    
    
    
     
  • 相关阅读:
    旧文备份:利用一个定时器实现多个虚拟定时器的两种方法
    TypeScript type 类型别名
    TypeScript 模块系统
    github----awesome-typescript-projects
    synchronous-request-with-websockets
    async await promise
    Sharing Configuration in ASP.NET Core SPA Scenarios
    Unicode String to a UTF-8 TypedArray Buffer in JavaScript
    MVC 访问静态页面 View 下面放JS
    Processing Binary Protocols with Client-Side JavaScript
  • 原文地址:https://www.cnblogs.com/ylfeiu/p/3403028.html
Copyright © 2020-2023  润新知