Re: inverse sort on key?
nooneinparticular314159@yahoo.com wrote:
I have an object (say, Car). Car contains some values, one of which
is speed. I want to store lots of cars in some sort of object that
will keep them sorted by speed. Some cars may have the same speed.
The catch is that I want to sort by highest speed, not lowest speed.
If I insert lots of cars into a TreeSet, with the key being the speed,
I get them in increasing order. If there are n cars with the same
speed, I get only one, because the keys are identical. I've been
unable to find an object that would work. I've tried implementing a
compare method in my object, and that doesn't help either. Any ideas?
--------------------------------------- 8< -------------------------
public class TestSortTree {
public static void main(String[] args) {
new TestSortTree();
}
TestSortTree() {
TreeSet<Car> set = new TreeSet<Car>();
set.add(new Car("Ford Edsel", 87));
set.add(new Car("Porshe Backhoe 1", 55));
set.add(new Car("Renault Twingo", 180));
set.add(new Car("Porshe Backhoe 2", 55));
for (Car car : set) {
System.out.println(car);
}
}
class Car implements Comparable<Car> {
private String name;
private int speed;
Car(String name, int speed) {
this.name = name;
this.speed = speed;
}
public String toString() {
return "Car: " + name + "; " + speed;
}
@Override
public int compareTo(Car other) {
if (speed != other.speed)
return other.speed - speed;
else
return (name.compareTo(other.name));
}
}
}
--------------------------------------- 8< -------------------------
Car: Renault Twingo; 180
Car: Ford Edsel; 87
Car: Porshe Backhoe 1; 55
Car: Porshe Backhoe 2; 55
This gives the sort order you desire. You can have multiple Cars with
the same speed but you can't have Cars with identical speed AND
identical names.
To summarize, the container object must:
1) Support sorting in inverse order (or another order of my choice)
2) Keep the objects sorted.
3) Support duplicate objects.
(I suppose I could sort on the negative value of the sort key, but...)
If the above doesn't doesn't answer your question I don't know the
answer - but I think Roedy once had a solution at
http://mindprod.com/products1.html#SORTED. I can't find it now.
I'd ignore requirement 2) if possible and use an ArrayList and then use
Collections.sort() when needed.
If 2) is essential, I think I'd consider using a LinkedList and insert
at the appropriate point. I think I'd wrap this up in something that
implements Collection. YMMV
Just my hastily dashed off ??0.02 worth.
--
RGB