Some primary usage of HashMap (new, traverse, add, find)

Create a new HashMap() object

This is the first step in using HashMap. The creation statement is as follows:

HashMap<Integer, Integer> map = new HashMap<>();

Note that the Key and Value of HashMap cannot be basic data types, but must be reference data types or wrapper data types. The reason for this is related to the underlying implementation principle of HashMap. Simply put, the basic data types cannot call the hashcode() and equals() methods.

Traverse HashMap()

for(Integer key: map.keySet()){
    
    }

The keySet() method can traverse the HashMap object, and can perform corresponding operations in the for statement block.

Add key-value pairs to HashMap object

Use the put(key, value) method to add key-value pairs to the HashMap object. Note that the data type must be consistent with the data type defined.

Find a value in a HashMap object

The get(key) method can return the corresponding value. When I was working on a force button question before, I thought I had to traverse to find out whether the key already existed. Later, I found that it can be solved by directly using the get(key) method and judging whether the return value is empty. This is also the characteristic of HashMap One, can reduce running time consumption.

————————————————————
Personal public account: "Chaqian". Usually, some programming-related articles will be updated, and everyone is welcome to pay attention~
tea move

Guess you like

Origin blog.csdn.net/weixin_46269688/article/details/114438893