What's wrong with "CompareTo" method?

C

Curious

I have an ArrayList, mBuyLimits. Each item on mBuyLimits is an
instance of class "LongTermLimitOnBuy" as defined below:

public class LongTermLimitOnBuy : LongTermLimit, IComparable
{
public LongTermLimitOnBuy(double price, int shares) : base
(price, shares)
{
}

// Sort by Price in descending order
public int CompareTo(object other)
{
LongTermLimitOnBuy lb = (LongTermLimitOnBuy)other;

if (this.Price >= lb.Price)
{
return 1;
}
else
{
return 0;
}
}
}

However, after I execute the following:

mBuyLimits.Sort();

The items on mBuyLimits are not sorted by Price in descending order.
They appear to be in random order. How come they are not sorted?
 
F

Family Tree Mike

Curious said:
I have an ArrayList, mBuyLimits. Each item on mBuyLimits is an
instance of class "LongTermLimitOnBuy" as defined below:

public class LongTermLimitOnBuy : LongTermLimit, IComparable
{
public LongTermLimitOnBuy(double price, int shares) : base
(price, shares)
{
}

// Sort by Price in descending order
public int CompareTo(object other)
{
LongTermLimitOnBuy lb = (LongTermLimitOnBuy)other;

if (this.Price >= lb.Price)
{
return 1;
}
else
{
return 0;
}
}
}

However, after I execute the following:

mBuyLimits.Sort();

The items on mBuyLimits are not sorted by Price in descending order.
They appear to be in random order. How come they are not sorted?

Because you are returning 0, meaning they are equal, only when they are
not equal. First try returning: this.Price.CompareTo(lb.Price)
 
C

Curious

Because you are returning 0, meaning they are equal, only when they are
not equal.  First try returning: this.Price.CompareTo(lb.Price)

Family Tree Mike,

Thanks! it works.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top