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.