I need to estimate if the array list is sorted (don't sort).
When Strings are sorted, they are in alphabetical order. I try to use compareTo() method to determine which string comes first
And return true if the array list is sorted, else false.
Code:
public boolean isSorted()
{
    boolean sorted = true;        
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i-1).compareTo(list.get(i)) != 1) sorted = false;
    }
    return sorted;
}
Easy test:
    ArrayList<String> animals = new ArrayList<String>();
    ArrayListMethods zoo = new ArrayListMethods(animals); 
    animals.add("ape");
    animals.add("dog");
    animals.add("zebra");
    //test isSorted
    System.out.println(zoo.isSorted());
    System.out.println("Expected: true");
    animals.add("cat");
    System.out.println(zoo.isSorted());
    System.out.println("Expected: false");
    animals.remove("cat");
    animals.add(0,"cat");
    System.out.println(zoo.isSorted());
    System.out.println("Expected: false");
    **Output:**
    false
    Expected: true
    false
    Expected: false
    false
    Expected: false
This easy test shows only 1/3 coverage.
How to solve this issue.
You have a small bug in your method. Should be :
public boolean isSorted()
{
    boolean sorted = true;        
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i-1).compareTo(list.get(i)) > 0) sorted = false;
    }
    return sorted;
}
>0 instead of !=1, you can't be sure that 1 is returned..
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