General Java: Declaring a static hashmap on class load?

Put your problem here if it does not fit any of the other categories.

General Java: Declaring a static hashmap on class load?

Postby certron » Tue Jan 29, 2008 4:53 pm

I have a static class that holds mostly 'final' variables and I have a hashmap that I'm using to speed lookups. The hashmap is created from two arrays that I've sorted by hand into the best order and I want the hashmaps to also be fully defined when the class is loaded. The class is static, most of the variables are static final, since they won't change.

Right now, I have this, which works but is sub-optimal:

StaticClass.makeMaps();
StaticClass.myMap.get("A");

I would like the hashmap to be defined in some definite way, but I don't know how to inline a Map definition.

I would like to just be able to do StaticClass.myMap.get("A"); and not have to initialize it with a command. Is this possible?
certron
Junior Developer
Junior Developer
 
Posts: 12
Joined: Tue Jan 29, 2008 4:42 pm

Top

Postby plusminus » Tue Jan 29, 2008 7:15 pm

Hello certron,

I created a litte (normal) Java Example that shows what you want to do (at least I think it is what you want to do :lol: ):
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public class MainClass{
  2.         public static void main(String[] args) {
  3.                 System.out.println("" + OtherClass.myMap.get("A"));
  4.         }
  5. }
  6.  
  7. class OtherClass{
  8.         public static HashMap<String, Integer> myMap = new HashMap<String, Integer>(){
  9.                 {
  10.                         this.put("A", 1337);
  11.                 }
  12.         };
  13. }
Parsed in 0.032 seconds, using GeSHi 1.0.8.4

So you create a anonymous HashMap-Inner-Type and place a implicit constructor within.
So you can fill the map before the first access to it.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby certron » Fri Feb 01, 2008 9:56 pm

I finally had time to try this out, and it worked great! Thanks so much, plusminus, and good luck with all your exams!
certron
Junior Developer
Junior Developer
 
Posts: 12
Joined: Tue Jan 29, 2008 4:42 pm

Postby plusminus » Fri Feb 01, 2008 10:24 pm

Hello certron,

no problem.
Thx 2/4 ran smoothly already :)

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: Yahoo [Bot] and 24 guests