Java – why are caps not sorted correctly here?
•
Java
I'm trying to sort items in list < string > This is an unordered list and how it is currently sorted:
Unsorted: [Pineapple,pineapple,apple,apricot,Banana,mango,Mango,melon,peach] Sorted: [apple,peach,Pineapple,pineapple]
Why didn't mango put in front of mango and pineapple?
This is my code:
import java.util.*; import java.lang.*; import java.io.*; class Test { public static void main (String[] args) throws java.lang.Exception { List<String> fruits = new ArrayList<String>(7); fruits.add("Pineapple"); fruits.add("pineapple"); fruits.add("apple"); fruits.add("apricot"); fruits.add("Banana"); fruits.add("mango"); fruits.add("Mango"); fruits.add("melon"); fruits.add("peach"); System.out.println("Unsorted: " + fruits); Collections.sort(fruits,new Comparator<String>() { @Override public int compare(String o1,String o2) { return o1.compareToIgnoreCase(o2); } }); System.out.println("Sorted: " + fruits); } }
Solution
You use comparetoignorecase () as the comparison method, so it compares' pineapple 'and' pineapple 'to 0 (the same string) and arranges them in the order they were sorted, because collections Sort guarantees that the same elements will not be reordered
Because the unordered list has' pineapple 'before' pineapple ', the comparison puts them in the sorted list in the same order These rules also apply to "mango" and "mango" The comparison method you are looking for is CompareTo (), which does consider uppercase and lowercase letters
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码