equals()方法练习
2024-10-09 03:45:58
1:
package com.aff.equals; public class TestOrder {
public static void main(String[] args) {
Order o1 = new Order(1001, "AA");
Order o2 = new Order(1001, "AA");
System.out.println(o1 == o2);// false
System.out.println(o1.equals(o2));// false--->true 重写equals方法后
}
} class Order {
private int orderId;
private String orderName; public int getOrderId() {
return orderId;
} public void setOrderId(int orderId) {
this.orderId = orderId;
} public String getOrderName() {
return orderName;
} public void setOrderName(String orderName) {
this.orderName = orderName;
} public Order(int orderId, String orderName) {
super();
this.orderId = orderId;
this.orderName = orderName;
} //比较两个order对象的属性是否完全相同,相同的话返回true
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof Order) {
Order o1 = (Order) obj;
return this.orderId == o1.orderId && this.orderName.equals(o1.orderName);
} else {
return false;
}
}
} 输出结果:
false
true
2:
package com.aff.equals; public class TestMyDate {
public static void main(String[] args) {
MyDate m1 = new MyDate(12, 3, 2012);
MyDate m2 = new MyDate(12, 3, 2012); if (m1 == m2) {
System.out.println("m1==m2");
} else {
System.out.println("m1!=m2");
}
// boolean java.lang.Object.equals(Object obj)
// 调用的为Object里面的equals方法,需要重写equals方法
if (m1.equals(m2)) {
System.out.println("m1 is equals m2");
} else {
System.out.println("m1 is not equal to m2");
}
}
} class MyDate {
private int day;
private int month;
private int year; public MyDate(int day, int month, int year) {
super();
this.day = day;
this.month = month;
this.year = year;
} public int getDay() {
return day;
} public void setDay(int day) {
this.day = day;
} public int getMonth() {
return month;
} public void setMonth(int month) {
this.month = month;
} public int getYear() {
return year;
} public void setYear(int year) {
this.year = year;
} //手动写的
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof MyDate) {
MyDate m = (MyDate) obj;
return this.day == m.day && this.month == m.month && this.year == m.year;
} else {
return false;
}
}
} 输出结果:
m1!=m2
m1 is equals m2
最新文章
- 两个单选按钮(一个是,一个否 ),一个div层,实现点击隐藏,显示div
- mybatis输出SQL
- Google Java编程风格指南中文版
- 新浪微博授权失败:applications over the unaudited use restrictions
- oracle decode(nvl(estimate_qty,0),0,1,estimate_qty) 函數
- WDC2106 iOS10新特性及开发者要注意什么
- SPRING IN ACTION 第4版笔记-第二章WIRING BEANS-007-以set方法注入<;property>;\p-namespace\util-space
- Objective-C中的分类与协议
- Linux crontab 命令详解(含配置文件路径)
- Destoon标签使用技巧十则
- 在code first结构下的生成的数据迁移文件,upadate-database失败
- ERP服务器简单维护
- css入门第一天
- Chapter 4 Invitations——9
- 解决Javascript中$(window).resize()多次执行(转)
- sleep()方法和yield()方法有什么区别?
- Vue---从后台获取数据vue-resource的使用方法
- re模块逐步进阶
- MVC仓储使用join
- 45度炸队Alpha冲刺博客集