”==“和”equals()”的区别

来源:互联网 发布:风险矩阵分析法 介绍 编辑:程序博客网 时间:2024/06/07 08:21


//  String str1 = "flyweight";
//  String str2 = "flyweight";
//  System.out.println(str1 == str2);  //输出true
  
//  String str1 = "fly";
//  String str2 = "weight";
//  String str3 = "flyweight";
//  String str4;
//  str4 = str1 + str2;
//  System.out.println(str3 == str4);// false
//  str4 = (str1 + str2).intern();
//  System.out.println(str3 == str4);// true
  
  /* == 运算符在Java中被用来比较两个名称是否引用至同一对象,
   * 所以不可以用==来比较两个字串的內容是否相同,比较的话要用equals*/
  String str1 = new String("bcterry");
     String str2 = new String("bcterry");
     System.out.println(str1 == str2);//false
     System.out.println(str1.equals(str2));//true

 

Object类中的equals方法和“==”是一样的,没有区别,而String类,Integer类等等一些类,是重写了equals方法,才使得equals和“==不同”,所以,当自己创建类时,自动继承了Object的equals方法,要想实现不同的等于比较,必须重写equals方法。

Java中的equals是十分重要的,和= =要区别开来,最近在看孙卫琴的JAVA面向对象编程一书,觉得对其阐述写的不错,所以现在小结其
主要内容,而且要将 = =和 equals列为重要的对比概念来学习

1、声明格式
    public  boolean equals(Object obj)

   其比较规则为:当参数obj引用的对象与当前对象为同一个对象时,就返回true,否则返回false.


比如以下两个对象animal1和animal2,引用不同的对象,因此用==或equals()方法比较的结果为false;而animal1和animal3变量引用同一个DOg对象,因此用= =或者equals()方法比较的结果为true.

   Animal  animal1=new Dog();
   Animal  animal2=new  Cat();
   Animal animal3=animal1;

则animal1==animal2   (FALSE)
   animal1.equals(animal2)  (false)

   animal1==animal3   (true)
   animal1.equals(animal3)   (true)


而JDK类中有一些类覆盖了oject类的equals()方法,比较规则为:如果两个对象的类型一致,并且内容一致,则返回true,这些类有:
java.io.file,java.util.Date,java.lang.string,包装类(Integer,Double等)


比如
Integer  int1=new Integer(1);
Integer int2=new Integer(1);


String str1=new String("hello");
String str2=new String("hello");

int1==int2   输出:false,因为不同对象
int1.equals(int2)   输出:TRUE


str1==str2   (false)
str1.equals(str2)   (true)
  当然,可以自定义覆盖object类的equals()方法,重新定义比较规则。比如,下面Person类的equals()比较规则为:只要两个对象都是Person类,并且他们的属性name都相同,则比较结果为true,否则返回false

public class Person{
   private String name;
   public Person(String name)
  {
     this.name=name;
   }
public boolean equals(Object o)
{
  if (this==0) return true;
if (!o instanceof Person) return false;
final Person other=(Person)o;
if (this.name().equals(other.name()))
    return true;
else
  return false;
}

}


注意,在重写equals方法时,要注意满足离散数学上的特性

1、自反性   :对任意引用值X,x.equals(x)的返回值一定为true.
2    对称性:   对于任何引用值x,y,当且仅当y.equals(x)返回值为true时,x.equals(y)的返回值一定为true;
3    传递性:如果x.equals(y)=true, y.equals(z)=true,则x.equals(z)=true
4   一致性:如果参与比较的对象没任何改变,则对象比较的结果也不应该有任何改变
5   非空性:任何非空的引用值X,x.equals(null)的返回值一定为false

原创粉丝点击