I have an ArrayList called account which contains Strings. I'm trying to write a method that checks if they are in order and returns true or false based on whether they are in order or not.
How would you go about this? I've already tried checking the initial chracter with a for-loop but it went terribly wrong. I created a new ArrayList and set it equal to the original, then sorted it and compared them but since they contained the same data it always came back true.
Just an extra quick question, since I'm doing this for Strings, how would you check if some numbers were in ascending/descending order? Throught the same principal?
Thankyou!
Try this (assuming you want to compare the strings using their natural ordering, of course):
String previous = ""; // empty string: guaranteed to be less than or equal to any other
for (final String current: thelist) {
if (current.compareTo(previous) < 0)
return false;
previous = current;
}
return true;
This is due to the fact that String
implements Comparable<String>
, and the comparison will be done using the strings' natural ordering.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With