我有两个同一类的对象(其中包含对象列表)。我需要查找两者是否相同。
考虑下面的例子:
class Device {
String deviceName;
String devLocation;
String devType;
String devID;
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDevLocation() {
return devLocation;
}
public void setDevLocation(String devLocation) {
this.devLocation = devLocation;
}
public String getDevType() {
return devType;
}
public void setDevType(String devType) {
this.devType = devType;
}
public String getDevId() {
return devID;
}
public void setDevId(String devId) {
this.devID = devId;
}
}
class DevList {
List<Device> deviceList;
public List<Device> getDevices() {
return deviceList;
}
public void setDevices(List<Device> deviceList) {
this.deviceList = deviceList;
}
}
需要比较DevList类的两个对象。
每个固定时间间隔都会获取一个新的 DevList 对象。
每次我需要用以前的对象验证当前对象并更新数据库(如果有任何差异),否则忽略。
当前对象和先前对象中的列表(deviceList) 的顺序可能不同。
例如:
考虑下面两个 Json 格式的对象(请忽略 json 格式错误)。
对象 1:
{
"devList":[
{
"deviceName":"ABC",
"devLocation":"India",
"devType":"Router",
"devID":"1111"
},
{
"deviceName":"XYZ",
"devLocation":"India",
"devType":"Router",
"devID":"2222"
}
]
}
对象2:
{
"devList":[
{
"deviceName":"XYZ",
"devLocation":"India",
"devType":"Router",
"devID":"2222"
},
{
"deviceName":"ABC",
"devLocation":"India",
"devType":"Router",
"devID":"1111"
}
]
}
我们可以通过检查 devID 来迭代两个对象中的列表来做到这一点。但复杂度为 M*N。
还有其他办法吗?
最佳答案
您可以重写 Device
中的 equals
来比较每个 Device
对象。
类似的东西
class Device {
...
...
//your getter and setter
public boolean equals (Object obj)
{
if (Device.class != obj.getClass()) {
return false;
}
if (obj instanceof Device) {
return (deviceName.equals(((Device) obj).deviceName) &&
devLocation.equals(((Device) obj).devLocation) &&
devType.equals(((Device) obj).devType) &&
devID.equals(((Device) obj).devID));
}
return false;
}
}
现在,请调用 removeAll
,这将从 List1
List1.equals(List2);
因此,如果两个列表具有相同的对象列表,则 List1
将为空。
关于java - 比较包含对象列表的同一类的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48704668/