Do I need to add metadata to Java collections?

Let's say I have a set of objects that can be sorted using several different comparators based on different fields of the object. It would be nice to find out later in the code that the comparator used to sort the collection, and if it was ascending or descending. Does it still do it elegantly instead of using a bunch of booleans to keep track of things?

+4
source share
3 answers

Not for the Collection interface, but if you use SortedSet , the comparator () method is used there, where you can request its comparator.

Otherwise, you will have to subclass the collection class that you use to add the accessories you need.

+2
source

There is nothing with the realities that do this. You will need to track this yourself. You can subclass the implementation of Collection to add fields containing this information.

You can also map implementations to metadata of your choice using a map - in particular, it seems that you want IdentityHashMap to do this because you do not want to compare two different collections for equality as keys with equal () keys.

I would keep the boolean (up / down) and Comparator link used for sorting, if that is what defines the sort completely. Or, if it is sorted by field, save the line that called the field, perhaps.

+1
source

what:

define methods for your decorated Collection<Foo>

 public List<Comparator<Foo>> getComparators() { ... } 

and

 public int whichComparator() { ... } 

which returns which Comparator is currently in use from the List . You can make it more attractive with Map and some reasonable keys (for example, enumerations - perhaps even enumerations that implement comparators) if you change which comparators can be used throughout the life of the object, but I think the above is a good enough start .

0
source

Source: https://habr.com/ru/post/1303616/


All Articles