What are the ways to initialize a hashmap?

  1. Create an empty HashMap object by using the constructor of the HashMap class.
HashMap<String, Integer> map = new HashMap<>();
  1. Create a HashMap object with a specified initial capacity and load factor using the HashMap class constructor.
HashMap<String, Integer> map = new HashMap<>(16, 0.75f);
  1. Add key-value pairs one by one using the put method of the HashMap class.
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
  1. Create an immutable Map object containing a single key-value pair using the static method singletonMap from the Collections class.
Map<String, Integer> map = Collections.singletonMap("key", value);
Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds