“==”与“equals”地小模小样

2019-04-13 17:00发布

“==一般用于数值类型地比较,equals多用于引用类型的比较 public static void main(String[] args) {
  int i=10;
  int j=10;
  double k=10.0;
  System.out.println(i==j);
  System.out.println(i==k);//操作类型不同,先将范围小的数值类型转化成范围大的类型
  TestEquals t1=new TestEquals();
  TestEquals t2=t1;
  TestEquals t3=new TestEquals();
  System.out.println(t1==t2);
  System.out.println(t1==t3);
  //String-->String单独分配了空间存储值,为了节省空间,r1,r2指向同一对象。
  String r1="abc";
  String r2="abc";
//new 关键字给r3,r4分配了不同空间,所以一般不直接new String();浪费内存
  String r3=new String("abc");
  String r4=new String("abc");
//String 重写了Object的equals及toString方法,String比较的不是地址,而是地址里面存储的值。
  System.out.println(r1.equals(r2));
  System.out.println(r3.equals(r2));
  System.out.println(r1.equals(r4));
//建一个学生类Student,比较是否是同一个对象 public class Student {
 private int age;  public Student(int age, String name, int height) {
  super();
  this.age = age;
  this.name = name;
  this.height = height;
 }
 private String name;
 private int height;
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getHeight() {
  return height;
 }
 public void setHeight(int height) {
  this.height = height;
 }
 public boolean equals(Object o) {
  if (o!=null&&o instanceof Student)//如果传过来的不是Student类型,先判断,强制转化之后,在比较
  {
   Student s = (Student) o;
   if (this.getAge() == s.getAge()&& this.getHeight() == s.getHeight()&& this.name.equals(s.name))
   {
    return true;
   }
   else
   {
    return false;
   }
  }
  else
  {
   return false;
  }
 }
 public String toString()
 {
  return this.getName()+","+this.getHeight()+",  "+this.getAge();
 }
 
}
  //当变量指向同一个对象:true。因为Student重写了equals及toString()方法。
  Student s1=new Student(18,"jing",180);
  Student s2=new Student(18,"jing",180);
  Object s3=s2;
  Student s4=new Student(18,"wang",180);
  System.out.println(s1.equals(s2));
  System.out.println(s3.equals(s2));
  System.out.println(s1.equals(s4));
  System.out.println(s1.equals(null));