Reputation: 383
I have two list of different class objects Tracker and Pet and combine these two lists to one list of class object PetManagement. Now I want to sort my PetManagement list like, Tracker that linked with Pets are at the start of the list and all that is not linked came after. So at the end my list should look like this:
position. Tracker - Pet
So I would have null objects in my list. I coded now for a while and end up in a lot of for loops, so I think there is better solution to get the same results. I worry that my code know is not really readable and easily produce issues.
Note: In my Tracker and Pet class I use a unique id for both to know which are linked, I also have a boolean in both (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...
}
Upvotes: 0
Views: 38
Reputation: 4623
I would just make your class comparable:
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;
}
}
Upvotes: 1