Java程序员技术干货

Java虚拟机常量池的认识

2017-08-18  本文已影响32人  咖啡机an

public static void main(String[] args) {
String str1 = new String("wwe");
String str2 = new String("wwe");
System.out.println(str1 == str2);
System.out.println(str1.intern() == str2.intern());

    Integer a1 = 1;
    Integer a2 = new Integer(1);
    System.out.println(a1.equals(a2));
    System.out.println(a1 instanceof Integer);
}

输出:false true true true

1.false 。 String str1 = new String("wwe"); String str2 = new String("wwe"); System.out.println(str1 == str2);类中的 ‘==’ 比较的是内存地址,通过new生成的对象会在堆中创建一个新的对象,内存地址明显不同。
2.trueSystem.out.println(str1.intern() == str2.intern());。String.intern(),比较的是常量池中的值。当常量池中不存在“wwe”时,会在常量池中新建一个常量。若存在,则直接返回该常量。
源码介绍如下:

/**
* 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();

一道思考题 new String("wwe").equals("11去去去") 创建了几个对象

这里创建了1或2 个对象。如果常量池不存在“11去去去”则需要创建一个对象。

3.true System.out.println(a1.equals(a2)); 以下是interger类型的equals函数,不同的复合类是不一样的

/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/

public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

4.true。 System.out.println(a1 instanceof Integer);

用来在运行时指出对象是否是特定类的一个实例

上一篇下一篇

猜你喜欢

热点阅读