Reputation: 1101
Currently, we are using Groovy as frontend and Java Spring as backend.
In groovy we define a property Map parameters = [:]
which will assign to private Map<String, Object> parameters;
in Java.
I have a question regarding the instance of this MAP interfaces in both languages. As I read groovy create by default instance of LinkedHashMap
and Java create by default instance of HashMap
is it true?
My overall requirement is to preserve the order of data, which LinkedHashMap
does but HashMap
not.
So as frontend is already LinkedHashMap
, it will pass ordered data into the backend.
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
Is it true?
Do I need to change model in JAVA (backend) from Map
to LinkedHashMap
?
Upvotes: 1
Views: 1588
Reputation: 37008
Map
is
an interface. So if you demand a Map
as argument or parameter, you
are only requesting those guarantees.
If you demand further guarantees (e.g. that LinkedHashMap preserve insertion order), then you are better off requesting that explicitly.
Since you are talking "backend" and "frontend" there is also the matter of transport between the two. If you are using transports (and not direct calls), that are no able to hold order in maps (e.g. JSON), then you are better off to not rely on the different data types. E.g. use a list of key-value tuples instead.
Groovy has a literal to quickly create maps ([:]
or forms with keys
like [a: 42]
). Those maps are LinkedHashMap
as you stated.
groovy:000> [:].getClass()
===> class java.util.LinkedHashMap
Since Java as of up to 15 has no literal for maps there is no "default" -- the default is what you make it.
In general it's best to always think about the data type you are actually in need of. This also means, that the map literal of Groovy can be the wrong choice.
Upvotes: 1
Reputation: 45319
As I read groovy create by default instance of LinkedHashMap and Java create by default instance of HashMap is it true?
Java, in fact, doesn't create any kind of map by default. The developer picks which Map
implementation they instantiate (almost always). Java doesn't have a counterpart for Groovy's map literal [:]
, so there's no "default" type to instantiate in Java. As for Groovy, it's true that the map literal creates a LinkedHashMap
:
groovy:000> [:].getClass()
===> class java.util.LinkedHashMap
So as frontend is already LinkedHashMap, it will pass ordered data into the backend. [...] is it true?
Yes. During runtime, the Map
object that's passed to setParameters()
will be as generated by your "front-end" code. The call would simply behave the same way as though you'd created a LinkedHashMap
from your Java code and passed it to the method.
The runtime won't re-shape the object into a HashMap
(even if it had to do something like that, making it a HashMap
would be curiously arbitrary). All that matters here is that the types are compatible, and LinkedHashMap
is a Map
.
Upvotes: 3