Solved

static maps

Posted on 2012-03-14
2
183 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.
0
Comment
Question by:dpalyca755
2 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 37721968
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
0
 
LVL 7

Accepted Solution

by:
gudii9 earned 500 total points
ID: 37722491
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
0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question