I am very new to Java, and especially the topics that I discuss below, but I spent a lot of time working through this and reading the answers previously asked on this site, and I don't really find anything right on the spot, so I thought it might be worth it.
My question is actually doubled. The actual problem I want to solve involves creating an order program, and I want to sort using price-time priority. The ultimate goal is to create a structure that looks like HasMap<ticker, TreeMap<Priority,Order>> , where Priority is the class I wrote that implements a comparator based first on price and then on time. Doing this led me to the questions I ask here (the actual setup of what I'm working on is not very relevant, but I want to make it clear why I'm looking at it).
Suppose I want to build a TreeMap using the K keys and V values. Then, of course, TreeMap needs to know how to compare objects in K My question is: if K already implements a comparator and defines a comparison method, will TreeMap read this? Or do I still need to specify a comparator in the constructor? The closest thing that I am fond of is that it is worth writing a comparator class in the class using TreeMap , as shown here: Java: SortedMap, TreeMap, Comparable? How to use?
Now, in fact, I still passed the constructor to the comparator, and it seems to be built just fine. But then when I try to pass this to the HashMap , I get an error. The code is as follows:
protected Comparator<Priority> priorityCompare; protected TreeMap<Priority, Order> _buy = new TreeMap<Priority, Order>((Comparator<? super Priority>) priorityCompare); protected HashMap<String, TreeMap<Priority, Order>> _buyBook; protected HashMap<String, TreeMap<Priority,Order>> _sellBook;
The problem is that I really want TreeMap inside HashMap use this Comparator , but Java gets angry when I do this. So my second question is: if you want to use such a structure (HashMap (-, TreeMap)), and you want TreeMap to use a custom comparator, how do you do it?
EDIT: I mentioned this above, but didn't show what I was talking about. Sorry about that. The situation in which I really would like is something like:
protected HashMap<String, TreeMap<Priority, Order>((Comparator<? super Priority>) priorityCompare)> _buyBook; protected HashMap<String, TreeMap<Priority,Order>((Comparator<? super Priority>) priorityCompare)> _sellBook;
This way, TreeMaps knows how I would like them to use the Comparator in the Priority class. However, after that, it gives me a syntax error (and just tells me to delete these tokens). I also tried passing _buy (as written in my source code field) as a value, but this did not work, and I immediately realized that it was stupid as soon as I did it. In any case, the question of how I can get TreeMap to know how I want it to compare keys in K, while inside the HashMap above, is the biggest question I have.