In: Computer Science
Write a class IgnoreCaseComparator that implements Comparator<Character>. If it were used as the argument to List.sort(), it would sort the list ignoring case. This behavior is different from using the natural ordering of characters, where uppercase characters come before lowercase characters.
Note that this question is not asking you to sort a list -- just to write the comparator!
For example, if the unsorted list were [b, C, A, d], then the list would be [A, b, C, d] after sorting using this comparator. (If you had sorted using the natural ordering of characters, the result would instead have been[A, C, b, d].)
You may find a utility method of Character, such as Character.toLowerCase(), helpful.
You may assume that Comparator and Character are imported. You may not import other classes.
Ok so the required code is attached below.
If you get any doubt feel free to drop that in the comment section.
Note: Code consist of a full program with the required (IgnoreCaseComparator) class and a main class just for testing the code. I know the full program is not demanded. but just for the test . you can easily copy the required class.
Code:
import java.util.*;
class IgnoreCaseComparator implements Comparator<Character>{
@Override
public int compare(Character o1, Character o2) {
// TODO It compares the character
in lowercase form
return
Character.toLowerCase(o1)-Character.toLowerCase(o2);
}
}
public class Main{
public static void main(String[] args) {
//For testing
ArrayList<Character> List=new
ArrayList<Character>();
List.add('a');
List.add('B');
List.add('D');
List.add('c');
List.sort(new
IgnoreCaseComparator());
System.out.println(List);
}
}