What's wrong with "CompareTo" method?

  • Thread starter Thread starter Curious
  • Start date Start date
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?
 
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)
 
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.
 
Back
Top