Java中的equals和==的差别 以及Java中等价性和同一性的讨论

==对基本数据类型比较的是值,对引用类型比较的是地址

equals()比较的是对象的数据的引用

等价性原理:

  • 自反性    x.equals(x)为true
  • 对称性    x.equals(y) 为true时,y.equals(x) 也为true
  • 传递性    若x.equals(y) 为true , y.equals(z) 为true, 则x.equals(z) 为true
  • 一致性   在未修改x,y的值的情况下x.equals(y)始终是相同的值
  • 非空性   x.equals(null) 总是 false
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int n=3;
        int m=3;
        String str1 = "hello";//"hello"存在于常量池,str1,str2都指向该常量池
        String str2 = "hello";

      
        System.out.println("基本数据类型的 ==  判定:"+(n==m));  //判断数据
        System.out.println("引用数据类型的 == 判定"+(str1==str2));//判断地址



        String str3 = new String("hello");//"hello"存在于堆的对象内存区,非常量区
        String str4 = new String("hello");
       
        System.out.println("对象的 == 判定:"+(str3 == str4)); //判断地址
        System.out.println("对象的 equals() 判定"+str3.equals(str4));//判断数据

        str4 = str3;
        System.out.println("对象赋值后的 == 判定"+( str3 == str4 ) );
        System.out.println("对象的 equals() 判定"+str3.equals(str4));
    }

}

结果如下:

基本数据类型的 ==  判定:true
引用数据类型的 == 判定true
对象的 == 判定:false
对象的 equals() 判定true
对象赋值后的 == 判定true
对象的 equals() 判定true

 

public class practice5 {

	public static void main(String[] args) {
		Dog spot = new Dog();
		Dog scruffy = new Dog();
		Dog spot1 = new Dog();
		Dog spot2 = new Dog();
		
		spot.setNameString("spot");
	   scruffy.setNameString("scruffy");
	   spot.setSayString("Ruff!");
	   scruffy.setSayString("Wurf!");
	   spot2.setNameString("spot");
	   spot2.setSayString("Ruff!");
	   
	   spot1=spot;
	   System.out.println(spot.getNameString()+"\t"+spot.getSayString());
	   System.out.println(scruffy.getNameString()+"\t"+scruffy.getSayString());
	   
	   System.out.println("spot1==spot\t"+(spot1==spot));
	   System.out.println("spot1.equals(spot)\t"+spot1.equals(spot));
	   
	   System.out.println("spot2==spot\t"+(spot2==spot));
	   System.out.println("spot2.equals(spot)\t"+spot2.equals(spot));
	   
	   System.out.println("spot2.nameString==spot.nameString\t"+(spot2.nameString==spot.nameString));
	   System.out.println("spot2.nameString.equals(spot.nameString)\t"+spot2.nameString.equals(spot.nameString));
	   
	   
	}

}
class Dog{
	
	String nameString;
	String sayString;
	
	public String getNameString() {
		return nameString;
	}
	public void setNameString(String nameString) {
		this.nameString = nameString;
	}
	public String getSayString() {
		return sayString;
	}
	public void setSayString(String sayString) {
		this.sayString = sayString;
	}
	
	
	
}

结果

spot	Ruff!
scruffy	Wurf!
spot1==spot	true
spot1.equals(spot)	true
spot2==spot	false
spot2.equals(spot)	false
spot2.nameString==spot.nameString	true
spot2.nameString.equals(spot.nameString)	true

 

全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务