Reputation: 1447
I have an ArrayList of notes in the form of strings (an example of one would be "take out the trash". I have a notes class and one of the methods is supposed to go through the notes stored in the ArrayList and find the one that comes first in the alphabet. This is my current method:
public String firstAlphabetically() {
String min = "";
for (int i = 0; i < notes.size(); i++) {
for (int j = i + 1; j < notes.size() + 1; i++) {
if ((notes.get(i)).compareTo(notes.get(j)) < 0) {
min = notes.get(i);
} else {
min = notes.get(j);
}
}
}
return min;
}
However, when I run the program, I get an out of bounds error on this line: for (int j = i + 1; j < notes.size() + 1; i++)
. I know what an out of bounds error is but I can't figure out what part of that line would cause the program to crash. Could anybody tell me what I am doing wrong?
Upvotes: 1
Views: 2869
Reputation: 425043
Problem 1:
The loop termination condition should be i < notes.size()
Problem 2:
Too much code. Try this 1-liner instead:
return notes.stream().sorted().findFirst().orElse(null);
Upvotes: 2
Reputation: 905
add:
implements Comparable<Note>
to your class signature and then implement the comparTo() method in your Note class. Then you can use:
Collections.sort(listOfNotes)
Upvotes: 0