RE: Java: Using Comparable to Establish Natural Order

  • From: "Ken Perry" <whistler@xxxxxxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Fri, 28 Nov 2008 17:01:41 -0500

Did you get this working I am just now catching up with mail.

Ken

-----Original Message-----
From: programmingblind-bounce@xxxxxxxxxxxxx
[mailto:programmingblind-bounce@xxxxxxxxxxxxx] On Behalf Of Jared Wright
Sent: Thursday, November 27, 2008 12:28 PM
To: programmingblind@xxxxxxxxxxxxx
Subject: Java: Using Comparable to Establish Natural Order

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

__________
View the list's information and change your settings at 
//www.freelists.org/list/programmingblind

Other related posts: