Android判断同一个类的两个对象的内容是否相同

本文探讨了在数据库操作中如何实现对请求的JSON对象的差异化处理,即在数据库已有相同数据时不进行更新,而是选择插入或更新。通过重写类的equals()和hashCode()方法来比较对象内容,并在Eclipse或Android Studio中自动生成代码,以确保在不完整数据存储的情况下正确处理差异。以一个特定的Program类为例,展示了如何实现这一过程。

在编写对数据库差异化处理的时候,差异化就是把请求的json对象存入数据库时,当数据库有相同的数据时不更新,否则更新或插入。这里需要取出数据库的数据封装成对象。

对于内容的比较,这里使用重写类的equal()和hashCoad()方法。使用eclipse或AndroidStudio可以帮助自动生成。由于项目中请求的json拼装的对象的内容并不全部存入数据库,这就需要我们在自动生成的时候选择适当的字段。例如:

package bean;

public class Program {
	public String programId = "";
	public String subitem_pk = "";
	public String item_url = "";
	public String title = "";
	public long timestamp = 0l;
	public long endtimeStamp = 0l;
	public String subitem_url = "";
	public boolean is_complex = true;
	public String poster_url = "";
	public String item_pk = "";
	public String model_name = "";

	public Program() {
	}

	

	public Program(String title, long timestamp, String poster_url,
			String item_pk) {
		super();
		this.title = title;
		this.timestamp = timestamp;
		this.poster_url = poster_url;
		this.item_pk = item_pk;
	}



	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		Program program = (Program) o;

		if (timestamp != program.timestamp) return false;
		if (title != null ? !title.equals(program.title) : program.title != null) return false;
		if (poster_url != null ? !poster_url.equals(program.poster_url) : program.poster_url != null)
			return false;
		return !(item_pk != null ? !item_pk.equals(program.item_pk) : program.item_pk != null);

	}

	@Override
	public int hashCode() {
		int result = title != null ? title.hashCode() : 0;
		result = 31 * result + (int) (timestamp ^ (timestamp >>> 32));
		result = 31 * result + (poster_url != null ? poster_url.hashCode() : 0);
		result = 31 * result + (item_pk != null ? item_pk.hashCode() : 0);
		return result;
	}

	@Override
	public String toString() {
		return "Program{" +
				"title='" + title + '\'' +
				", timestamp=" + timestamp +
				", poster_url='" + poster_url + '\'' +
				", item_pk='" + item_pk + '\'' +
				'}';
	}
}

测试的代码如下:

package main;

import bean.Animal;
import bean.Program;

public class Equal {
	public static void main(String[] args) {		
		Program p1 = new Program("title", 100l, "poster_url", "item_pk");
		Program p2 = new Program("title", 100l, "poster_url", "item_pk");
		System.out.println(p1.equals(p2));
		
		Program p3 = new Program("title", 100l, "poster_url", "item_pk");
		p3.programId = "1";
		Program p4 = new Program("title", 100l, "poster_url", "item_pk");
		p4.programId = "2";
		System.out.println(p3.equals(p4));
	}
}


选择的方式如下:



Android 开发中,**判断两个时间是否为同一天** 是一个常见需求,比如: - 判断用户签到是否是“今天” - 比较日志记录日期 - 控制每日任务、提醒等 虽然看起来简单,但如果不注意时区和时间精度,很容易出错。 --- ## ✅ 正确方法:使用 `Calendar` 或 `java.time`(推荐)比较年、月、日 ### 🔁 方法一:使用 `Calendar`(兼容所有 Android 版本) ```java public static boolean isSameDay(long time1, long time2) { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTimeInMillis(time1); cal2.setTimeInMillis(time2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH); } ``` #### ✅ 使用示例: ```java long now = System.currentTimeMillis(); long yesterday = now - 24 * 60 * 60 * 1000; long tomorrow = now + 24 * 60 * 60 * 1000; Log.d("DateCompare", "now 和 yesterday 同一天?" + isSameDay(now, yesterday)); // false Log.d("DateCompare", "now 和 tomorrow 同一天?" + isSameDay(now, tomorrow)); // false Log.d("DateCompare", "now 和 now 同一天?" + isSameDay(now, now)); // true ``` > ⚠️ 注意:`Calendar.MONTH` 是从 0 开始的(0=1月),但我们在比较时无需处理偏移,因为两个值都遵循相同规则。 --- ### 🔁 方法二:使用 `java.time.LocalDate`(Android API 26+ 推荐) 如果你的目标设备是 Android 8.0(API 26)及以上,可以使用现代 `java.time` API: ```java @TargetApi(Build.VERSION_CODES.O) public static boolean isSameDay(long time1, long time2) { Instant instant1 = Instant.ofEpochMilli(time1); Instant instant2 = Instant.ofEpochMilli(time2); ZoneId zoneId = ZoneId.systemDefault(); // 使用系统默认时区 LocalDate date1 = instant1.atZone(zoneId).toLocalDate(); LocalDate date2 = instant2.atZone(zoneId).toLocalDate(); return date1.isEqual(date2); } ``` #### ✅ 优点: - 更简洁、语义清晰 - 不受 `Calendar` 的可变性影响 - 性能更好 #### 📦 兼容低版本?使用 **ThreeTenABP** 库 对于 API < 26,你可以引入 [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) 来使用 `java.time` 功能: ##### 1. 添加依赖(`app/build.gradle`) ```gradle implementation 'com.jakewharton.threetenabp:threetenabp:1.4.0' ``` ##### 2. 初始化(在 `Application.onCreate()` 中) ```java AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); AndroidThreeTen.init(this); ``` ##### 3. 使用 `LocalDate` 判断同一天 ```java // 需要导入 org.threeten.bp.* import org.threeten.bp.Instant; import org.threeten.bp.ZoneId; import org.threeten.bp.LocalDate; public static boolean isSameDay(long time1, long time2) { Instant instant1 = Instant.ofEpochMilli(time1); Instant instant2 = Instant.ofEpochMilli(time2); ZoneId zoneId = ZoneId.systemDefault(); LocalDate date1 = instant1.atZone(zoneId).toLocalDate(); LocalDate date2 = instant2.atZone(zoneId).toLocalDate(); return date1.isEqual(date2); } ``` --- ### 🔁 方法三:通过格式化字符串比较(不推荐用于性能敏感场景) ```java public static boolean isSameDay(long time1, long time2) { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); String date1 = fmt.format(new Date(time1)); String date2 = fmt.format(new Date(time2)); return date1.equals(date2); } ``` #### ❌ 缺点: - 创建字符串开销大 - 多线程下 `SimpleDateFormat` 不安全 - 可读性强但效率低 ✅ 仅适用于调试或低频调用场景 --- ## ✅ 常见错误与注意事项 | 错误做法 | 说明 | |--------|------| | `time1 / 86400000 == time2 / 86400000` | 忽略了时区问题!UTC 时间可能导致“跨天”偏差 | | 直接比较 `Date` 对象 | `Date` 包含时分秒,必须截断才能比 | | 忽视夏令时 | 跨夏令时边界可能导致计算错误 | 📌 正确做法的关键是:**基于本地日期(Local Date)进行比较,考虑时区** --- ## ✅ 扩展:封装成工具 ```java public class DateUtils { /** * 判断两个时间戳是否属于同一个自然日(按本地时区) */ public static boolean isSameDay(long time1, long time2) { Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTimeInMillis(time1); cal2.setTimeInMillis(time2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH); } /** * 获取今天的 00:00:00 时间戳(用于判断是否今天) */ public static long getStartOfToday() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTimeInMillis(); } /** * 判断某个时间是否是“今天” */ public static boolean isToday(long time) { return isSameDay(time, System.currentTimeMillis()); } } ``` #### 使用示例: ```java if (DateUtils.isToday(userLoginTime)) { showDailyReward(); } ``` --- ## ✅ 总结对比 | 方法 | 是否推荐 | 兼容性 | 是否考虑时区 | 备注 | |------|----------|--------|---------------|------| | `Calendar.get(YEAR/MONTH/DAY)` | ✅ 推荐 | API 1+ | ✅ 是 | 最通用方案 | | `java.time.LocalDate` | ✅ 强烈推荐(API 26+) | API 26+ | ✅ 是 | 现代 Java 时间 API | | `ThreeTenABP` | ✅ 推荐(低版本替代) | API 14+ | ✅ 是 | 第三方库支持 | | 格式化为 `"yyyy-MM-dd"` | ⚠️ 可用 | 所有版本 | ✅(依赖 Locale) | 效率较低 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值