Implements Comparable to get alphabetical sort with Strings

return name.compareTo(otherObject.name);

String already implements Comparable so you don't need do to anything.


I think you want something like this

package mine;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MyObject {
    private String name;

    public MyObject(String name) {
        this.name = name;
    }

    public MyObject() {
        // TODO Auto-generated constructor stub
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }



    @Override
    public String toString() {
        return "MyObject [name=" + name + "]";
    }

    public static void main(String[] args){
        List<MyObject> l = new ArrayList<>();
        l.add(new MyObject("Ab"));
        l.add(new MyObject("AA"));
        l.add(new MyObject());

        Collections.sort(l, new Comparator<MyObject>(){

            @Override
            public int compare(MyObject o1, MyObject o2) {
                if (o1.name == null && o2.name == null){
                    return 0;
                }else if (o1.name == null){
                    return -1;
                }else if (o2.name == null){ 
                    return 1;
                }else{
                    return o1.name.toUpperCase().compareTo(o2.name.toUpperCase());
                }
            }

        });

        System.out.println(l);
    }
}

You are overthinking the problem. Strings have their own natural ordering, which is alphabetic, so you can just use the String.compareTo like this:

@Override
public int compareTo(MyObject otherObject) {
    return this.name.compareTo(otherObject.name);
}