Title: Use Java's HashMap.put() function to add mapping relationships to HashMap
Introduction:
In Java programming, using HashMap is very common and important. HashMap is a collection of key-value pairs that can store and retrieve data. This article will focus on how to use Java's HashMap.put() function to add a mapping relationship to a HashMap, and illustrate it with code examples.
import java.util.HashMap; public class HashMapPutExample { public static void main(String[] args) { // 创建一个新的HashMap对象 HashMap<String, Integer> hashMap = new HashMap<>(); // 向HashMap中添加映射关系 hashMap.put("apple", 10); hashMap.put("banana", 15); hashMap.put("orange", 8); // 打印HashMap的内容 System.out.println("HashMap中的映射关系为:" + hashMap); } }
In the above sample code, we first create A HashMap object is obtained, the key type is String, and the value type is Integer. Then, use the HashMap.put() function to add three mapping relationships to the HashMap, namely "apple" and 10, "banana" and 15, and "orange" and 8.
Finally, we printed the contents of the HashMap through the System.out.println() function.
Result Analysis
Running the above example code, we can get the following output:
HashMap中的映射关系为:{orange=8, apple=10, banana=15}
It can be seen that the mapping relationship in HashMap is in an unordered manner Stored with keys and values separated by "=" symbols.
Reference materials:
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
The above is the detailed content of Use java's HashMap.put() function to add mapping relationships to HashMap. For more information, please follow other related articles on the PHP Chinese website!