The comparator's job is simply to say which of two objects comes first - there's no mechanism to manipulate the underlying collection during it's comparisons. I think you would want to think about this in a slightly different way: perform your filtering logic prior to adding an object to your collection.
I'd recommend just using a standard list, say ArrayList
for sake of simplicity. Also you'd need to override the equals()
method in your Vehicle class which returns true
if two Vehicles share the same IDs and part numbers.
When it comes to adding new vehicles you can do something like this:
int vehicleIndex = myvehicles.indexOf(vehicle) // -1 if missing, otherwise 0 or greater to represent the index position
if (vehicleIndex == -1) {
// No item in the list shares the ids/model/part numbers so can add
myvehicles.add(vehicle)
} else {
// There's another similar vehicle, better compare their notes:
Vehicle existingVehicle = myvehicles.get(vehicleIndex); // retrieve the object from list so that we can compare it
// check if the new vehicle has longer notes
if (vehicle.getOurNotes().length > existingVehicle.getOurNotes().length) {
// if it does, remove the old one from the list
myvehicles.remove(vehicleIndex);
// and add the new one. Effectively we've done a replacement
myvehicles.add(vehicle)
}
}
Obviously it's not automatically sorted but you can do that after adding a batch of items by running the Collections.sort() method which also accepts a Comparator, but this time your comparator can focus on the specific task of detailing the ordering now that you know the list is pre-filtered so you are not concerned with trying to filter items out.