[英]How to compare two Arraylists which contain objects of the same class in Java?
[英]compare two objects of same class which contain list of objects
我有兩個相同類的對象(包含對象列表)。我需要查找兩個對象是否相同。
考慮以下示例:
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對象。
每次我需要與先前的對象驗證當前對象並更新DB時,是否有其他區別,否則將忽略。
當前對象和先前對象中的list(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
將為空。
第1步:首先在設備類中重寫equal方法第2步:用以下邏輯覆蓋DevList類中的equal():使用一個Set集合2.從1st Object的列表中添加對象3.檢查set的size() 3.從第二個對象的列表中添加對象5.每次從第二個列表中添加時,都要檢查set的size()6.如果大於一個列表的大小,則不相等( As Set將不保留重復值 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.