String中的intern方法】的更多相关文章

上一篇你真的会用String吗(3)-关于字符串拼接中我们提到了String.intern()方法,本篇我们就来详细的看下这个方法是干嘛的.首先来看下jdk8中这个方法的注释: 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…
我们用一个经典的例子来理解 package com.jvm.heap; public class MyTest { public static void main(String[] args) { String str1 = new StringBuilder("计算机").append("软件").toString(); System.out.println(str1.intern() == str1); String str2 = new StringBuild…
一.intern()定义及使用 相信绝大多数的人不会去用String类的intern方法,打开String类的源码发现这是一个本地方法,定义如下: public native String intern(); 文档告诉我们该方法返回一个字符串对象的内部化引用.关于native方法详解见native关键字(本地方法). java调用so动态链接库 java.lang.String.intern():返回一个保留池字符串,就是一个在全局字符串池中有了一个入口.如果以前没有在全局字符串池中,那么它就会…
JVM的知识这里总结的很详细:https://github.com/doocs/jvm/blob/master/README.md,因此在本博客也不会再对其中的东西重复总结了. intern的作用 简单的讲,intern方法是把调用者丢到常量池里,并返回一个引用. String s = new String("sq") + new String("666"); //line1 String s1 = s.intern(); //line2 以上代码line1在堆里创…
二话不说,先来说下重写的事情: 在Java中,String .Math.还有Integer.Double....等这些封装类重写了Object中的equals()方法,让它不再比较其对象在内存中的地址,而是比较对象中实际包含的整数的值,即比较的是内容.再强调一次,Object的equals()方法比较的是地址值,所以Object equals相等时,其hashcode必然相等,因为都是对象的地址,所以自己定义的类如果要加入到集合类中一定要记得重写这两个方法. 在Eclipse中重写hashcod…
今天在看一本书的时候注意到一个String的intern()方法,平常没用过,只是见过这个方法,也没去仔细看过这个方法.所以今天看了一下.个人觉得给String类中加入这个方法可能是为了提升一点点性能,因为从常量池取数据比从堆里面去数据要快一些.(个人感觉) API上的那几句关于这个方法,其实总结一句就是调用这个方法之后把字符串对象加入常量池中,常量池我们都知道他是存在于方法区的,他是方法区的一部分,而方法区是线程共享的,所以常量池也就是线程共享的,但是他并不是线程不安全的,他其实是线程安全的,…
一般我们变成很少使用到 intern这个方法,今天我就来解释一下这个方法是干什么的,做什么用的 首先请大家看一个例子: public static void main(String[] args) throws Exception { String a = "b" ; String b = "b" ; System.out.print( a == b); String c = "d" ; String d = new String( "…
该方法的作用是把字符串加载到常量池中(jdk1.6常量池位于方法区,jdk1.7以后常量池位于堆) 在jdk1.6中,该方法把字符串的值复制到常量区,然后返回常量区里这个字符串的值: 在jdk1.7里,该方法在常量区记录该字符串首次出现的实例引用,然后返回该地址,常量区可以保存字面量也可以保存字符串对象在堆中的引用. String s3 = new String("123") + new String("123"); s3.intern(); String s4 =…
0.引言 什么都先不说,先看下面这个引入的例子:   String str1 = new String("SEU")+ new String("Calvin");   System.out.println(str1.intern() == str1);   System.out.println(str1 == "SEUCalvin"); 本人JDK版本1.8,输出结果为:   true   true 再将上面的例子加上一行代码:   String…
0.引言 什么都先不说,先看下面这个引入的例子: String str1 = new String("SEU")+ new String("Calvin"); System.out.println(str1.intern() == str1); System.out.println(str1 == "SEUCalvin"); 本人JDK版本1.8,输出结果为: true true 再将上面的例子加上一行代码: String str2 = &quo…