How do I make 2 comparable methods in only one class?

前端 未结 3 1708
借酒劲吻你
借酒劲吻你 2020-11-29 01:21

I\'ve got one class, that I sort it already by one attribute. Now I need to make another thing, that I need to create another way to sort my data. How can I make it, so I ca

3条回答
  •  余生分开走
    2020-11-29 02:07

    If the two methods require the exact same footprint, you may be inappropriately overloading a single class with multiple uses, which would be resolved by fixing your class hierarchy - like instead of using "shape", subclass it with "oval", "rectangle", etc.

    If subclassing doesn't make sense, you need to create different comparison classes. In Java, you often use a Comparator for comparisons. Create several (or create a configurable comparator): IsbnComparator, AuthorComparator, etc.

    Oh, and the configurable option would be:

     BookComparator implements Compartor {
       enum FIELD { AUTHOR, ISBN, ... };
       setSortOrder(int rank, FIELD field){...}
     }
    

提交回复
热议问题