Java 初始化HashMap

Java 初始化HashMap

HashMap是java.util包的一部分。HashMap扩展了一个抽象类AbstractMap,它也提供了一个Map接口的不完全实现。它以(Key, Value)对的形式存储数据。

我们可以通过四种不同的方式使用构造函数初始化HashMap:

1.HashMap()

它是默认的构造函数,初始容量为16,负载系数为0.75。

HashMap hs=new HashMap()。

// Java program to demonstrate simple initialization 
// of HashMap
import java.util.*;
public class GFG {
    public static void main(String args[])
    {
        HashMap<Integer, String> hm = new HashMap<Integer, String>();
        hm.put(1, "Ram");
        hm.put(2, "Shyam");
        hm.put(3, "Sita");
        System.out.println("Values " + hm);
    }
}

输出:

Values {1=Ram, 2=Shyam, 3=Sita}

2.HashMap(int initialCapacity)

它用于在默认负载系数0.75下创建一个具有指定初始容量的空HashMap对象。

HashMap hs=new HashMap(10)。

// Java program to demonstrate initialization 
// of HashMap with given capacity.
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
        HashMap<Integer, String> hm = new HashMap<Integer, String>(3);
        hm.put(1, "C");
        hm.put(2, "C++");
        hm.put(3, "Java");
        System.out.println("Values of hm" + hm);
    }
}

输出:

Values of hm{1=C, 2=C++, 3=Java}

3.HashMap(int initial capacity, float loadFactor)

它用于创建一个具有指定初始容量以及负载系数的空HashMap对象。

HashMap hs=new HashMap(10, 0.5)。

// Java program to demonstrate initialization 
// of HashMap with given capacity and load factor.
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
        HashMap<Integer, String> hm =
               new HashMap<Integer, String>(3, 0.5f);
        hm.put(1, "C");
        hm.put(2, "C++");
        hm.put(3, "Java");
        System.out.println("Values of hm" + hm);
    }
}

输出:

Values of hm{1=C, 2=C++, 3=Java}

4.HashMap(Map map)

它用于通过使用给定的Map对象map的元素来初始化哈希图。

HashMap hs=new HashMap(map)。

// Java program to demonstrate initialization 
// of HashMap from another HashMap.
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
        HashMap<Integer, String> hm = new HashMap<Integer, String>();
        hm.put(1, "C");
        hm.put(2, "C++");
        hm.put(3, "Java");
        System.out.println("Values of hm" + hm);
  
        // Creating a new map from above map
        HashMap<Integer, String> language = new HashMap<Integer, String>(hm);
  
        System.out.println("Values of language " + language);
    }
}

输出:

Values of hm{1=C, 2=C++, 3=Java}
Values of language {1=C, 2=C++, 3=Java}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程