CompareTo z nullami na końcu

0

Mam problem z metodą compareTo, chodzi o to, że mogą się pojawić nulle a te mają być na końcu. Analogicznie do order by ... nulls last. Proszę o pomoc bo albo mam gdzieś jeszcze coś źle albo to ta metoda, wyglądała tak a muszę zrobić, żeby nulle szły ostatnio i coś mi nie wychodzi.

  
@Override
    public int compareTo(Object o) {
        if( getParam() == null) {
            return -1;
        }
        if ( o.getParam() == null ) {
            return 1;
        }
        return getParam().getDescription().compareTo(o.getParam().getDescription());
    }
1
  1. Nie masz rzutowania o na typ w ramach którego jest metoda.
  2. compareTo jest generyczna po to by nie musieć używać Object i rzutowania
  3. jeżeli getDescription zwróci null dla parametru do którego referencję trzyma obiekt na którym wywołujesz metodę to dostaniesz NPE.

A teraz co do implementacji:

public int compateTo(TwojaKlasaWKtorejSiedziTaMetoda o){
   if(o==null || o.getParam() == null )
     return 1; // jesteśmy > niż null
   if(getParam()==null || getParam().getDescription()==null)
     return -1; // jesteśmy nullem i tym samym jesteśmy mniejsi
   return getParam().getDescription().compareTo(o.getParam().getDescription());
}
0

Poradziłem sobie w ten sposób:

public int compareTo(ObiektKlasy... o) {
   
         if( getParam().getDescription() == null) {
            return 1;
        }
        if ( o.getParam().getDescription() == null ) {
            return -1;
        }
        
        if(getParam().getDescription() == null && o.getParam().getDescription() == null)
            return 0;
        else if(getParam().getDescription() > o.getParam().getDescription())
            return 1;
        else if(getParam().getDescription() < o.getParam().getDescription())
            return -1;

        return getParam().getDescription().compareTo(o.getParam().getDescription());
 
    }

1 użytkowników online, w tym zalogowanych: 0, gości: 1