Java uses the get() function of the HashMap class to obtain the values in the collection
HashMap is one of the commonly used collection classes in Java. It provides a storage method of key-value pairs that can be quickly passed key to get the value. In HashMap, we can use the get() function to obtain the value corresponding to the specified key. This article will introduce how to use the get() function of HashMap and provide some usage examples.
First, we need to import the package where the HashMap class is located:
import java.util.HashMap;
Then, we can create a HashMap object and add key-value pairs to it:
HashMap<String, Integer> map = new HashMap<>(); map.put("apple", 10); map.put("banana", 5); map.put("orange", 8);
In the above In the example, we create a HashMap object and use "apple", "banana" and "orange" as keys and 10, 5 and 8 as the corresponding values.
Next, we can use the get() function to get the value corresponding to the specified key:
int appleCount = map.get("apple"); System.out.println("苹果的数量是:" + appleCount);
In the above example, we get the key "apple" through get("apple") "corresponding value and assign it to the appleCount variable. Then, we use the System.out.println() function to print out the number of apples.
In addition to basic type values, we can also store objects of other classes into HashMap and obtain these objects through the get() function. For example, we can create a HashMap to store student objects:
class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } HashMap<Integer, Student> studentMap = new HashMap<>(); studentMap.put(1, new Student("张三", 18)); studentMap.put(2, new Student("李四", 20)); studentMap.put(3, new Student("王五", 22)); Student student = studentMap.get(1); System.out.println("学生姓名:" + student.getName()); System.out.println("学生年龄:" + student.getAge());
In the above example, we created a HashMap object to store student objects. The key is the student number and the value is the corresponding student object. Then, we obtain the student object with key 1 through get(1) and assign it to the student variable. Finally, we can get the student's name and age by calling the getName() and getAge() functions of the student object and print them out.
To summarize, using the get() function of HashMap can easily obtain the value corresponding to the specified key in the collection. We can store basic type values or objects of other classes into HashMap and obtain these values or objects through the get() function. I hope the examples in this article can help readers better understand the use of HashMap's get() function.
The above is the detailed content of Java uses the get() function of the HashMap class to obtain the values in the collection. For more information, please follow other related articles on the PHP Chinese website!