比较对象
我有一个表单,允许用户输入有关地址信息的值。 我想将从用户那里获得的值与存储在数据库中的 ADDRESS 表中的信息进行比较。 我有一个实体类
public class Address {
private String gevernate;
private int homeNo;
private String neighborhood;
private String street;
}
,它表示为数据库中名为 ADDRESS 的表。
我有一个此类的视图对象,它从 db tabel 返回所有地址值
public static Address getAddress(Connection Con, long stdID) {
// select stamatment and result set object.
}
我面临的问题是表单可能不包含Address对象的所有值,它可能只包含2个或3个值,它是在运行时指定的。如何比较两个对象?
I have a form that let user enter values about address information.
I want to compare the values I get from user, with information stored into ADDRESS table in the database.
I have an entity class
public class Address {
private String gevernate;
private int homeNo;
private String neighborhood;
private String street;
}
which is represented as a table in the database called ADDRESS.
and I have a view object for this class which return all address values from db tabel
public static Address getAddress(Connection Con, long stdID) {
// select stamatment and result set object.
}
The problem I face is that the form may NOT contain all values of Address object, it may contains only 2 or three values, it's specified at run time. How can I compare two objects ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
向类中添加 equals 方法,如下所示:
add an equals method to the class like this:
为 Address 对象定义/覆盖 equals() 和 hashcode()。比较如下:
Define/override equals() and hashcode() for the Address object. Compare as follows:
我会创建一个完全独立的类来进行比较,因为它们可能涉及特殊的逻辑和运行时配置。随着应用程序的增长,它可能涉及一些非常复杂的内容,例如匹配州(
NY
与New York
)等。不要使用
equals()
为此,应该是对 Java 集合和通用“这个对象是否完全相同”问题有意义的任何实现。基本思想:
由
AddressComparer
中的代码根据表单配置的用途来确定需要应用哪些规则,并执行所有这些特殊用途的小技巧。I would create an entirely separate class to do the comparisons, because they probably involve special logic and run-time configuration. As your application grows, it might involve some very complex stuff like matching states (
NY
versusNew York
), etc.Do not use
equals()
for this, which should instead be whatever implementation makes sense for Java collections and general-purpose "is this object exactly the same or not" questions.Basic idea:
It's up to the code in
AddressComparer
to figure out what rules it needs to apply based on what the form was configured to do, and to do all those little special purpose tricks.我只是调用这个伪代码,因为我不了解 Java:
I'll just call this pseudocode, because I don't know Java: