0

This is my Scheduler Class that sorts the arraylist. I made a custom compareTo method that returns an int value of 1, -1 or 0.

private ArrayList<Event> events = new ArrayList<Event>();


public Scheduler(ArrayList<Event> events){


    for (int i=0; i<events.size(); i++)
    {
        this.events.add(events.get(i));

    }

} 

public ArrayList<Event> getSchedule(){
    int i;
    int j;
    int N = events.size();


        for (i = 0; i <=(N-1); i++)
    {
        for(j = 1; j <= N;j++)
        {

    if(events.get(i).getEndTime().compareTo(events.get(j).getEndTime()) > 0){
                Collections.swap(events, i, j);
            }
        }   
    }

    return events;
}

I call it later in my UI class

Scheduler s = new Scheduler(events);

        System.out.println("Schedule:");

    for(int i = 0; i<s.getSchedule().size(); i++){
        System.out.println(s.getSchedule().get(i)); 
        }

It's giving me an IndexOutofBoundError. Why is it giving me this error, and how can I fix it

Jay-z
  • 1
  • 2
  • 1
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Joe C Dec 03 '16 at 22:45
  • for (i = 0; i <=(N-1); i++) change to for (i = 0; i <(N-1); i++) – MikeJRamsey56 Dec 04 '16 at 03:07

1 Answers1

0

In your getSchedule() method you are iterating i to N-1 and j to N with N being the size of the list. A list of n objects has the indexes 0 to n-1, so when accessing index n you try to access the data after the last element of the list which gives you an IndexOutOfBoundException.

A quick solution might be to set N to another value, which should be size - 1:

int N = events.size() - 1;

Even better: if you implemented a custom compareTo() method then you can implement the Comparable interface and then just use Collections.sort(events) instead of sorting the events yourself.

jCoder
  • 2,289
  • 23
  • 22
  • ok, changing the N got rid of the indexoutbounds error. But I realized that I have a problem in my compareTo method. `public int compareTo(Time that){ if(this.getHour() < that.getHour()) { return 1; } else if(this.getHour() > that.getHour()) { return -1; } else{ if(this.getMinute() < that.getMinute()) { return 1; } else if(this.getMinute() > that.getMinute()) { return -1; } return 0; }` This is preventing me from swapping since no matter what it will return the default value. Seems like an easy fix, but i cant get it – Jay-z Dec 03 '16 at 23:32
  • I tried some similar code and it seemed to work. The only thing I see in your code is that `compareTo` should return a negative value when `this` is lesser than `that` (according to Java 8 Javadoc). Did you yet debug through the `compareTo` method? – jCoder Dec 03 '16 at 23:40