GreatBambino
GreatBambino

Reputation: 51

Comparing elements in an arraylist

I have to check to see if the "tokens" in the arraylist are in increasing order.

private E[] data;      // where the data is stored   
private int size;      // how many items have been added to the list

public TopSpinArray(int numTokens, int spinSize)
{
    super(numTokens, spinSize);

    data = (E[])(new Object[numTokens]);
    size = 0;
} 

public boolean isSolved()
{     
    for(int i = 0; i < numTokens; i++)
    {
        if(data[i] < data[i+1])
        { 
            return true;
        }
    }
    return false;
}

when I compile, it says "bad operand types for binary operator '<' first type: E; second type: E"

how do I check to see if they are increasing?

Upvotes: 0

Views: 5048

Answers (1)

Keppil
Keppil

Reputation: 46209

The operator < is only valid for certain types of objects. To be able to compare any comparable type of object (I take your E to imply that your tokens indeed implement Comparable, since otherwise your question makes no sense,) you can use compareTo():

for(int i = 0; i < numTokens - 1; i++) {
     if(data[i].compareTo(data[i+1]) > 0) { 
         return false;
     }
}
return true;

Upvotes: 4

Related Questions