覆盖自我引用对象(父/子关系)的compareTo

时间:2011-10-29 00:46:19

标签: sorting grails compareto

我正在尝试在grails中的域类上实现compareTo,因此我可以返回一个SortedSet。我希望我的排序集按父母名称排序,然后按“子”名称排序。例如(P = parent,C = child):

  • P-1
    • C-1
    • C-2
  • P-2
    • C-3
    • C-4

我的班级看起来像这样:

class Issue implements Comparable {
 String name
 Issue parent

@Override
public int compareTo(obj){
  if(obj.parent!=null && this.parent!=null){
   parent.name.compareTo(obj.parent.name)
  }else{
      //What do I compare to sort the children relative to their parents?
  }
}

1 个答案:

答案 0 :(得分:3)

如果您要查找的只是排序集,那么只是在问题上实现Comparable并在映射上使用排序顺序就足够了吗?

class Issue implements Comparable {
 String name
 Issue parent
 SortedSet children

 static hasMany = [children : Issue]
 static belongsTo = [parent : Issue]
 static mapping = {
    sort 'name'
    children sort:'name'
 }    

@Override
public int compareTo(obj){
  if(obj){
    this.name?.compareTo(obj.name)
  }
}