java中==和equals以及hashcode的区别

== 在java中是运算符,用来比较两个变量是否相等。具体而言,当两个变量是基本数据类型(byte,short,char,int,long,float,double,boolean),就可以直接用==来比较两个变量是否相等。如果变量指向的数据是对象(引用类型),那么涉及到两块内存。变量本身存储的是这个对象的实际存储地址的首地址,而对象本身存储在堆内存中。此时比较两个变量==,实际上是比较两个对象存储地址的首地址是否相等。

equals是java中类Object提供的方法之一。所以每个类都有equals方法。理论上equals和==一样,都是比较的是引用。但是每个类的equals方法都可以被覆盖,所以可以通过覆盖的方法让它不是比较引用而是比较数据内容。如果一个类没有定义equals方法,那么此时使用equals方法就是使用==运算符。

hashcode()方法返回的是一个hash码,hash码的主要用途就是在对对象进行散列的时候作为key输入,据此很容易推断出,我们需要每个对象的hash码尽可能不同,这样才能保证散列的存取性能。hashCode()方法是从Object类中继承过来的,它也用来鉴定两个对象是否相等。Object类中的hashCode()方法返回对象在内存中地址转换成的一个int值,所以如果没有重写hashCode()方法,任何对象的hashCode()方法都是不相等的。

以下有个例子:

publicstaticvoid main(String[] args) {  

int int1 =12;  

int int2 =12;  

Integer Integer1 =new Integer(12);  

Integer Integer2 =new Integer(12);  

Integer Integer3 =new Integer(127);  

Integer a1 =127;  

Integer b1 =127;  

Integer a =128;  

Integer b =128;  

String s1 ="str";  

String s2 ="str";  

String str1 =new String("str");  

String str2 =new String("str");  

System.out.println("int1==int2:" + (int1 == int2));  

System.out.println("int1==Integer1:" + (int1 == Integer1));  

System.out.println("Integer1==Integer2:" + (Integer1 == Integer2));  

System.out.println("Integer3==b1:" + (Integer3 == b1));  

System.out.println("a1==b1:" + (a1 == b1));  

System.out.println("a==b:" + (a == b));  

System.out.println("s1==s2:" + (s1 == s2));  

System.out.println("s1==str1:" + (s1 == str1));  

System.out.println("str1==str2:" + (str1 == str2));  

    } 

输出结果:

int1==int2:true

int1==Integer1:true //Integer会自动拆箱为int,所以为true

Integer1==Integer2:false//不同对象,在内存存放地址不同,所以为false

Integer3==b1:false//Integer3指向new的对象地址,b1指向缓存中127地址,地址不同,所以为false

a1==b1:true

a==b:false

s1==s2:true

s1==str1:false

str1==str2:false

Integer b1 = 127;java在编译的时候,被翻译成-> Integer b1 = Integer.valueOf(127);

你可能感兴趣的:(java中==和equals以及hashcode的区别)