本文主要是介绍JVM的heap堆与常量池详解以String数值定义为例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、JDK里面定义的String实体类的equals方法
String使用对比俩个字符串使用equals比较友好,因为方法首先是比较引用地址,然后对比其中存储的数值。
//这是JDK里面String的方法。equals对比的是先对比引用地址,然后对比引用内容 public boolean equals(Object anObject) {if (this == anObject) {return true;}if (anObject instanceof String) {String anotherString = (String)anObject;int n = value.length;if (n == anotherString.value.length) {char v1[] = value;char v2[] = anotherString.value;int i = 0;while (n-- != 0) {if (v1[i] != v2[i])return false;i++;}return true;}}return false;}
2、JVM堆与常量池的含义
public static void main(String[] args) {testJVMHeap() ;}public static void testJVMHeap() {String str1 = "testJVMHeap";//str1 指向字符串常量池中的对象,如果有,则直接将 str1 指向"testJVMHeap"";String str2 = new String("testJVMHeap");//堆中创建一个新的对象String str3 = new String("testJVMHeap");//堆中创建一个新的对象System.out.println("str1==str2 : " +str1==str2);//falseSystem.out.println("str2==str3 : " +str2==str3);//falseSystem.out.println("str1.equals(str2) : "+str1.equals(str2));System.out.println("str2.equals(str3) : "+str2.equals(str3));}运行结果:
false
false
str1.equals(str2) : true
str2.equals(str3) : true
3、使用堆和常量池来解释这样的现象
直接存储在常量池中的定义绿色显示。
new String对象使用 String 提供的 intern 方法。String.intern() 是一个 Native 方法,它的作用是:如果运行时常量池中已经包含一个等于此 String 对象内容的字符串,则返回常量池中该字符串的引用;如果没有,JDK1.7之前(不包含1.7)的处理方式是在常量池中创建与此 String 内容相同的字符串,并返回常量池中创建的字符串的引用,JDK1.7以及之后的处理方式是在常量池中记录此字符串的引用,并返回该引用。
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
4、equals与==的区别显然一见
== 对比的是常量池里面的地址,
equals对比的是对象&常量池里面的地址
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
这篇关于JVM的heap堆与常量池详解以String数值定义为例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!