javasortingcomparetoalphabetical

Characters beyond Z in alphabetic order


Ok, this is just a quick question since I'm not able to find the answer myself. In lists of Strings that are ordered alphabetically, using the Collections.sort and compareTo functions, what is the last available character (beyond "ZZZ")?

I would like to know characters beyond "ZZZ" in compareTo's order, out of curiosity.


Solution

  • Quote by Holger:

    You are comparing Strings not characters. The last String, i.e. the String for which no “greater” String exists, is a String consisting of 2147483647 repetitions of the character '\uFFFF'. You don’t want to use that…

    I consider this as the correct answer to my question asked.


    PS: For those wondering, this was the code in the original question:

    Reason why I asked the question:

    Collections.sort(myObjectList, new Comparator<MyObject>(){
        @Override
        public int compare(MyObject o1, MyObject o2){
            String name1 = o1.getName();
            String name2 = o2.getName();
    
            if(name1 == null)
                name1 = "ZZZ"; // <- Last String in compareTo's order
            if(name2 == null)
                name2 = "ZZZ"; // <- Last String in compareTo's order
    
            return name1.compareTo(name2);
        }
    });
    

    Changed to the following instead to solve my issue:

    Collections.sort(myObjectList, new Comparator<MyObject>(){
        @Override
        public int compare(MyObject o1, MyObject o2){
            String name1 = o1.getName();
            String name2 = o2.getName();
    
            if(name1 == null && name2 == null)
                return 0;
            if(name1 == null) // && name2 != null
                return 10;
            if(name2 == null) // && name1 != null
                return -10;
            else // name1 != null && name2 != null
                return name1.compareTo(name2);
        }
    });