John
John

Reputation: 111

How to use compareTo while iterating through an array

What is the correct way to use the compareTo inside for loop? I'd like to sort the Course objects in ascending order inside the array. I'm worried about the correct syntax for compareTo inside a loop in my insert() method.

if((array[i].courseNumber.compareTo(object.courseNumber)) <= 0) - is giving me error.

public class Courses implements Comparable{
    private String title;
    private int courseNumber;
    private Courses[] array;
    private int size;

    public Courses(String title, int courseNumber){
        this.title = title;
        this.courseNumber = courseNumber;
        this.array = new Courses[10];
        this.size = 0;
    }

    public void insert(String title, int courseNumber){
        Courses object = new Courses(title, courseNumber);
        if(size == 0){
            array[0] = object;
        }
        else{
            int i;
            for(i = 0; i < size; i++){
                if((array[i].courseNumber.compareTo(object.courseNumber)) <= 0)
                    //do STUFF
            }
        }

    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof Courses){
            Courses obj1 = (Courses)o;

            return this.courseNumber - obj1.courseNumber;
        }
        return -1;
    }
}

Upvotes: 1

Views: 1648

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191844

if((array[i].courseNumber.compareTo(object.courseNumber)) <= 0)

Is giving you an error because courseNumber is a primitive (not an object), so there is no compareTo method defined on it.

If you would like to use that syntax to compare integers, you can use the static Integer.compare method.

if(Integer.compare(array[i].courseNumber, object.courseNumber) <= 0)

If you want to use your defined compareTo method then do

if(array[i].compareTo(object) <= 0)) 

Upvotes: 1

FallAndLearn
FallAndLearn

Reputation: 4135

Hint : You are not passing the object as parameter.

How does this compare two objects ?

for(i = 0; i < size; i++){
                if((array[i].courseNumber.compareTo(object.courseNumber)) <= 0)
                    //do STUFF
            }

You should look at Arrays.sort(Object[]) which will take care about ordering it using the Comparable interface.

Upvotes: 0

Related Questions