📜  java hashmap int int - Java (1)

📅  最后修改于: 2023-12-03 14:42:14.356000             🧑  作者: Mango

Java HashMap

HashMap is a class in Java that implements the Map interface using a hash table. It stores key-value pairs and provides constant-time performance for the basic operations of put, get, and remove.

Declaring a HashMap

To declare a HashMap with integer keys and integer values, use the following syntax:

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

You can use the put method to add values to the HashMap:

map.put(1, 10);
map.put(2, 20);
map.put(3, 30);

System.out.println(map); // {1=10, 2=20, 3=30}
Accessing Values

You can use the get method to access values in the HashMap:

int value = map.get(1);
System.out.println(value); // 10
Removing Values

You can use the remove method to remove values from the HashMap:

map.remove(2);

System.out.println(map); // {1=10, 3=30}
Iterating over HashMap

You can use the entrySet method to get a set of key-value pairs, then use a for-each loop to iterate over the entries:

for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    int key = entry.getKey();
    int value = entry.getValue();
    System.out.println(key + "=" + value);
}

This will output:

1=10
3=30
Conclusion

HashMap is a useful class in Java for storing key-value pairs with constant-time performance for basic operations. With the syntax and methods outlined above, you can easily declare, add, access, remove, and iterate over values in a HashMap.