This is my method which used to populate a map, and there's other data will be added in the future.
public class myClass{
public Map populateMap(client: RedissonClient) {
Map map = client.getMap("map");
map.put(k1, v1);
map.put(k2, v2);
...
return map;
}
}
The problem is, each time when I calling this method in my main function, it will re-create the same map content again and again, is there a way to define it as a constant map object, not in a method.
Map map = myClass.populateMap(client);
...
From your question, it's not completely clear whether the map should belong to the instance or to the class.
To create a class constant map, use Map::of
:
class MyClass {
static final Map<String, String> MAP = Map.of("k1", "v1", "k2", "v2");
}
The abovementioned map is an unmodifiable map : it is guaranteed that no modifications could ever be made to the map 1 . If you want to get the contents of this map into a new map, in order to add additional data to it, just use
Map<String, String> newMap = new HashMap<>(MyClass.MAP);
newMap.put(...);
1 Well, perhaps it is possible with reflection. But for reflection applies: only use it if you know what you're doing.
if you make the method static, you can initialize a static map:
public class MyClass{
public static Map<String, String> map = populateMap();
private static Map<String, String> populateMap() {
Map<String, String> map = new HashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
...
return map;
}
}
now the populated MyClass.map
is accessible to all the other classes
It is actually already said, make the map a global constant, or in java terms: a static final field .
public class myClass {
private static final Map<String, String> MAP = new HashMap<>();
static {
MAP.put(k1, v1);
MAP.put(k2, v2);
}
Or since java 9 easier done as (thanks to @GhostCat):
private static final Map<String, String> MAP =
Map.of(k1, v1,
k2, v2);
Use typing, like the interface Map<Integer, Object>
. And for the creation pick the implementing class.
static {... }
is called a static initializer .
You can make it as a global variable like mentioned above.
public final static Map<String, String> MAP = populateMap();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.