Java: Using Comparable to Establish Natural Order

  • From: Jared Wright <wright.jaredm@xxxxxxxxx>
  • To: programmingblind@xxxxxxxxxxxxx
  • Date: Thu, 27 Nov 2008 12:27:36 -0500

Hi all, I've used comparable before, but with this go 'round I have found I must be missing something. I'm trying to use Comparable to establish the natural order of an Item class. Each item has a cost, size, and with these two values, the "value" of the item can be calculated. I wish for this value metric to be the index for the items' natural ordering, so priority queues and collection sorting methods will use this to order item objects. With the below code, my items are all returned to me from a priority queue simply in the reverse order they were added to the queue. Suggestions aappreciated, and I'll give much thanks on this of all days for any help! *grin* I am trying to have it order items with highest values first.


Best,
JW


// Class representing an item.
class Item implements Comparable {
   private double cost=0; private double size=0;
   public Item(double dCost, double dSize) {
       cost = dCost;
       size = dSize;
   }
   public double getCost() {
       return cost;
   }
   public double getSize() {
       return size;
   }
   public double getValue() {
       return cost/size;
   }
   public int compareTo(Object oItem) {
       double oItemValue = ((Item)oItem).getValue();
       double result = ((this.getValue()))-oItemValue;
       return (int)result;
   }
   }
__________
View the list's information and change your settings at //www.freelists.org/list/programmingblind

Other related posts: