Search code examples
javalistclassindexingcomparable

Is acceptable use static object for implementing comparable in java?


I have some class, for which I need implement

compareTo

I need particular order like (pseudocode):

static List: item1 item2 item3 ...

I would like use

List.indexOf(itemN) and compare to List.indexOf(itemM)

Does this solution acceptable?


Solution

  • Yes, it's acceptable, but unless your list is really small, it will be very inefficient. Indeed, every time you'll compare two elements, it will have to iterate through the list to find the index of the first element, and iterate again to find the index of the other one. This will be extremely inefficient.

    You'd better transform the List<Item> to a HashMap<Item, Integer> holding the index of every item in the list. Or use Guava's explicit ordering, which does that for you.