“==”:表示一个运算符,而equals是一个方法
==:可以使用在基本数据类型和引用数据类型变量中
1.如果比较的是基本数据类型,则是对两个变量保存的数据是否相等进行比较
int i = 10;
int j = 10;
double a = 10.0;
System.out.println(i == j); // true
System.out.println(i == a); // true
char c = 10;
System.out.println(i == c); // true
char c1 = 'A';
char c2 = 65;
System.out.println(c1 == c2); // true
2.如果比较的是引用数据类型,则是对两个对象的地址值是否相等进行比较,即两个引用是否为同一个对象
// 实例化Customer.创建customer和customer2两个对象
Customer customer = new Customer("tome", 12);
Customer customer2 = new Customer("tome", 12);
// 输入两个对象比较值情况
System.out.println(customer == customer2); // false
// Customer类
public class Customer {
String name;
int age;
// 构造器;
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
}
Equals方法的使用:
1.equals是一个方法而非运算符
2.只能使用于引用数据类型中
3.在Object类中,equals和==的作用是相同的,比较的是两个对象的地址值是否相同
// Object类中equal的方法
public boolean equals(Object obj) {
return (this == obj);
}
4.像String、Date、file等包装类都重写了Object类中的equals()方法,重写后,比较的不是两个引用地址是否相同,而是比较两个对象的实体内容是否相同
Date date = new Date(2019, 7, 25);
Date date2 = new Date(2019, 7, 25);
// 打印Date类的比较结果
System.out.println(date.equals(date2)); // true
String string = new String("guigu");
String string2 = new String("guigu");
// 打印String类的比较结果
System.out.println(string.equals(string2)); // true
自定义类使用equals.也通常比较的是两个对象的实体内容是否相同,因此需要对Object类的equals进行重写,来比较两个对象的实体内容是否相同
Customer customer = new Customer("tome", 12);
Customer customer2 = new Customer("tome", 12);
System.out.println(customer.equals(customer2));// true
// Customer类
public class Customer {
String name;
int age;
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
// 重写Object类中的equals方法,同Customer对象的age,name内容进行比较
@Override
public boolean equals(Object obj) {
if (this == obj) {
// 如果二者相等,直接返回true
return true;
}
// 使用instanceof,向下转型,以防出现ClassCastException的异常
if (obj instanceof Customer) {
// 类型强转
Customer customer = (Customer) obj;
// 比较两个对象的每个属性是否形同
if (this.age == customer.age && this.name.equals(customer.name)) {
return true;
} else {
return false;
}
}
return false;
}
}
通常,如果要使用自定义类进行比较的时候,可以直接生成对equals的重写方法