When using Collection.sort in Java what should I return when one of the inner objects is null
Example:
Collections.sort(list, new Comparator
Following the answer from Nikita Rybak, i'm already have a enum comparator, and only add the null logic from here.
public enum Orden implements Comparator {
ByStrDescripcion {
public int compare(CmunParametrosDTO item1, CmunParametrosDTO item2) {
if (item1.getStrDescripcion() == null && item2.getStrDescripcion() == null)
return 0;
if (item1.getStrDescripcion() == null)
return 1;
else if (item2.getStrDescripcion() == null)
return -1;
return item1.getStrDescripcion().compareTo(item2.getStrDescripcion());
}
}
public abstract int compare(CmunParametrosDTO item1, CmunParametrosDTO item2);
public Comparator ascending() {
return this;
}
public Comparator descending() {
return Collections.reverseOrder(this);
}
}
In this form i can call the sort method on my list.
if(isBolOrdAscendente()) Collections.sort(listado, CmunParametrosDTO.Orden.ByStrDescripcion .ascending());
else Collections.sort(listado, CmunParametrosDTO.Orden.ByStrDescripcion .descending());