![](/img/trans.png)
[英]how to merge two different List objects into one List and sort them
[英]Sort a list of two different class objects
我有兩個不同的 class 對象Tracker和Pet的列表,並將這兩個列表組合成一個 class object PetManagement的列表。 現在我想對我的 PetManagement 列表進行排序,例如,與 Pets 鏈接的 Tracker 位於列表的開頭,所有未鏈接的都在后面。 所以最后我的列表應該是這樣的:
position。 追蹤器 - 寵物
所以我的列表中有 null 對象。 我現在編碼了一段時間並最終進入了很多 for 循環,所以我認為有更好的解決方案來獲得相同的結果。 我擔心我的代碼知道不是真正可讀並且容易產生問題。
注意:在我的Tracker和Pet class 中,我使用唯一的 id 來讓兩者知道哪些是鏈接的,我在兩者中也有一個 boolean(hasTracker/hasPet)。
public class PetManagement {
private Pet pet;
private Tracker tracker;
public PetManagement(Pet pet) {
this.pet = pet;
}
public PetManagement(Tracker tracker) {
this.tracker = tracker;
}
public PetManagement(Pet pet, Tracker tracker) {
this.pet = pet;
this.tracker = tracker;
}
public Pet getPet() {
return pet;
}
public Tracker getTracker() {
return tracker;
}
}
public class Pet {
private Double id;
private String name;
private ImageView picture;
private String race;
private float weight;
private float height;
private Sex gender;
private boolean isCastrated;
private boolean isSterilized;
private int chipId;
private boolean hasTracker;
private Double trackerId;
public Pet(Double id, String name, ImageView picture, String race, float weight, float height, Sex gender, boolean isCastrated, boolean isSterilized, int chipId, boolean hasTracker, Double trackerId) {
this.id = id;
this.name = name;
this.picture = picture;
this.race = race;
this.weight = weight;
this.height = height;
this.gender = gender;
this.isCastrated = isCastrated;
this.isSterilized = isSterilized;
this.chipId = chipId;
this.hasTracker = hasTracker;
this.trackerId = trackerId;
}
getter and setter...
}
public class Tracker {
private Double id;
private String serialNum;
private boolean hasPet;
private Double petId;
public Tracker(double id, String serialNum) {
this.id = id;
this.serialNum = serialNum;
}
public Tracker(Double id, String serialNum, boolean hasPet, Double petId) {
this.id = id;
this.serialNum = serialNum;
this.hasPet = hasPet;
this.petId = petId;
}
getter and setter...
}
我只會讓您的 class 具有可比性:
public class PetManagement implements Comparable<PetManagement> {
...
@Override
public int compareTo(PetManagement other) {
boolean thisLinked = this.hasTracker() && this.hasPet();
boolean otherLinked = other.hasTracker() && other.hasPet();
if (thisLinked && !otherLinked)
return -1;
else if (!thisLinked && otherLinked)
return 1;
return 0;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.