Skip to content
Fix Code Error

How can I initialise a static Map?

March 13, 2021 by Code Error
Posted By: fahdshariff

How would you initialise a static Map in Java?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other method?

What are the pros and cons of each?

Here is an example illustrating the two methods:

import java.util.HashMap;
import java.util.Map;

public class Test {
    private static final Map<Integer, String> myMap = new HashMap<>();
    static {
        myMap.put(1, "one");
        myMap.put(2, "two");
    }

    private static final Map<Integer, String> myMap2 = new HashMap<>(){
        {
            put(1, "one");
            put(2, "two");
        }
    };
}

Solution

The instance initialiser is just syntactic sugar in this case, right? I don’t see why you need an extra anonymous class just to initialize. And it won’t work if the class being created is final.

You can create an immutable map using a static initialiser too:

public class Test {
    private static final Map<Integer, String> myMap;
    static {
        Map<Integer, String> aMap = ....;
        aMap.put(1, "one");
        aMap.put(2, "two");
        myMap = Collections.unmodifiableMap(aMap);
    }
}
Answered By: Hemal Pandya

Related Articles

  • SQLException: No suitable Driver Found for…
  • How can I resolve Web Component Testing error?
  • Examples of GoF Design Patterns in Java's core libraries
  • Vue.JS & Spring Boot - Redirect to homepage on 404
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • I want to create a SQLite database like in the…
  • How to filter a RecyclerView with a SearchView
  • How to generate JAXB classes from XSD?
  • Fastest way to iterate over all the chars in a String
  • insert tables in dataframe with years from 2000 to…
  • Using enums in a spring entity
  • How to draw interactive Polyline on route google…
  • Unable to run Robolectric and Espresso with a…
  • Checking if a variable is an integer in PHP
  • EL access a map value by Integer key
  • Creating a singleton in Python
  • How should I choose an authentication library for…
  • When I'm testing a web app by JUnit and Mockito I…
  • java: HashMap not working
  • What is the difference between the HashMap and Map…
  • Vaadin Spring Boot - There was an exception while…
  • Format Column Data before passing to Vue Good-Table
  • Showing/Hiding Table Rows with Javascript - can do…
  • Item position in RecyclerView only changing when…
  • TLS 1.3 server socket with Java 11 and self-signed…
  • How to directly initialize a HashMap (in a literal way)?
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • Why do we need Rc when immutable references can do the job?
  • Draw in Canvas by finger, Android
  • How to print binary tree diagram?
  • Effectively getting items from map based on specific sort
  • Auto-fit TextView for Android
  • SecurityException: Permission denied (missing…
  • How to "properly" create a custom object in JavaScript?
  • Javax.net.ssl.SSLHandshakeException:…
  • Composition or Inheritance for classes with almost…
  • java.lang.ClassNotFoundException: HttpServletRequest
  • Chain-calling parent initialisers in python
  • How to download and save an image in Android
  • Correct way to initialize HashMap and can HashMap…
  • How to fix Hibernate LazyInitializationException:…
  • android studio 0.4.2: Gradle project sync failed error
  • Autowiring fails: Not an managed Type
  • Eclipse will not start and I haven't changed anything
  • ClassNotFoundException:…
  • Type safety: Unchecked cast
  • What is and how to fix…
  • HQL Responding with…
  • Could not install Gradle distribution from…
  • Builder pattern without inner class
  • How to iterate (keys, values) in JavaScript?
  • String to HashMap JAVA
  • How to declare global variables in Android?
  • How to convert java.util.Date to java.sql.Date?
  • Neither BindingResult nor plain target object for…
  • Most efficient way to increment a Map value in Java
  • Difference between
  • Error creating bean with name 'entityManagerFactory'…
  • Android app unable to start activity componentinfo
  • How do I keep only the first map and when the game…
  • Requested bean is currently in creation: Is there an…
  • Google Maps Android API v2 - Interactive InfoWindow…
  • Exception in thread "JobGenerator"…
  • Initialising mock objects - MockIto
  • org.hibernate.MappingException: Could not determine…
  • Tomcat 7 "SEVERE: A child container failed during start"
  • C++ map and unordered_map: emplace to do an…
  • org.springframework.beans.factory.BeanCreationExcept…
  • How to parse JSON file with Spring
  • Error creating bean with name
  • Typescript Symbol.species typing inference
  • How do I address unchecked cast warnings?
  • RxJava Main Thread Always Crash
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Playing HTML5 video on fullscreen in android webview
  • MessageBodyWriter not found for media…
  • Can we instantiate an abstract class?
  • Restful API service
  • IOException: read failed, socket might closed -…
  • Ukkonen's suffix tree algorithm in plain English
  • Jetpack Compose and Hilt Conflict
  • Smart way to truncate long strings
  • java IO Exception: Stream Closed
  • How do I pass variables and data from PHP to JavaScript?
  • How to for each the hashmap?
  • What is a NullReferenceException, and how do I fix it?
  • Drawing a simple line graph in Java
  • Flattening/normalizing deeply nested objects with…
  • Store an array in HashMap
  • Nested class: Calling child class properties in parent class
  • WAVE file unexpected behaviour
  • Jetty server throws idle timeout for REST calls
  • Usage of __slots__?
  • How do I use 3DES encryption/decryption in Java?
  • How to test Spring Data repositories?
  • Determine project root from a running node.js application
  • Render HTML to an image
  • Cannot get hash map value as ArrayList
  • Change private static final field using Java reflection
  • Why postman indicated 404 not found

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to randomize (shuffle) a JavaScript array?

Next Post:

Tab key == 4 spaces and auto-indent after curly braces in Vim

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error