Java中的==和equals,常量池

对于Java基本类型(byte,char,short,int,long,double,float,boolean),利用==判断相等。

对于基本类型的包装类(Integer,Boolean等),integer1.equals(int1)==true,integer1.equals(integer2)==false

对于普通对象,==运算符判断是否指向同一引用对象,equals通过对象所属类的equals实现方式判断相等。

         int int1=1;
         int int2=1;
         Integer integer3=1;
         System.out.println("int1==int2: "+(int1==int2));
         System.out.println("int1==integer3: "+(int1==integer3));
         System.out.println("integer3.equals(int1): "+(integer3.equals(int1)));

         Double double1=1.0;
         Double double2=1.0;
         System.out.println("double1==double2: "+(double1==double2));
         System.out.println("double1.equals(double2): "+double1.equals(double2));

         String string1="string";
         String string2="string";
         System.out.println("string1==string2: "+(string1==string2));
         System.out.println("string1.equals(string2): "+(string1.equals(string2)));

         String string3=new String("string");
         String string4=new String("string");

         System.out.println("string3==string4: "+(string3==string4));
         System.out.println("string3.equals(string4): "+(string3.equals(string4)));
int1==int2: true
int1==integer3: true
integer3.equals(int1): true
double1==double2: false
double1.equals(double2): true
string1==string2: true
string1.equals(string2): true
string3==string4: false
string3.equals(string4): true

常量池大体可以分为:静态常量池,运行时常量池。

静态常量池 存在于class文件中

运行时常量池,在class文件被加载进了内存之后,常量池保存在了方法区中,通常说的常量池 值的是运行时常量池。

1. 基本类型包装类的常量池:

java中基本类型的包装类的大部分都实现了常量池技术,两种浮点数类型的包装类Float,Double并没有实现常量池技术。
即Byte,Short,Integer,Long,Character,Boolean,这5种包装类默认创建了数值[-128,127]的相应类型的缓存数据,但是超出此范围仍然会去创建新的对象。

Integer类中有 IntegerCache

为了节省内存,JVM会缓存-128到127(默认)的Integer对象。因此,i1,i2实际指向同一个对象。

Integer i1 = 100;
Integer i2 = 100;
System.out.println(i1==(i2)); //true

Integer i1 = 1000;
Integer i2 = 1000;
System.out.println(i1==(i2)); //false

2. String类的常量池

String s1="string";

String s2=new String("string");

第一种方式是在常量池中拿对象,第二种方式是直接在堆内存空间创建一个新的对象。
使用new方法,便需要创建新的对象。

https://www.jianshu.com/p/c7f47de2ee80

https://blog.csdn.net/qq_41376740/article/details/80338158

原文地址:https://www.cnblogs.com/cnsec/p/13547589.html