We help IT Professionals succeed at work.

static maps

dpalyca755
dpalyca755 asked
on
Medium Priority
202 Views
Last Modified: 2012-03-24
How do I implement a static map class to be used by a few other classes?
examples to follow will be great.
Comment
Watch Question

Awarded 2011
Awarded 2011

Commented:
can you please elaborate?

HashMap as any Java object can be made static and then you could address it by refereinng to the class name rather than the instance of the class where it is a field
So if you declare it like that:
class ClassName {
public static HashMap<Integer, String> map;
...


}

Thane in any other class of your applucation you can address it like that:

ClassName.map.get(key)

thsi is no different form any other static object
Commented:
Here is interesting explanation, links

public static Map CONSTANTS = new HashMap() { {
put("key1", "value1");
put("key2", "value2");
}};


Even better is to wrap the ArrayList/HashMap by passing them to Collections.unmodifiableList or Collections.unmodifiableMap. Thus making sure that it is truly a constant list/map.

http://livinginjava.blogspot.com/2010/08/initialize-static-list-and-map.html
http://stackoverflow.com/questions/507602/how-to-initialise-a-static-map-in-java

Explore More ContentExplore courses, solutions, and other research materials related to this topic.