基础操作
put(K key, V value):将指定的键值对插入到 HashMap 中,若键已存在,则更新值。
get(Object key):根据键获取值,如果不存在该键,返回 null。
remove(Object key):根据键删除键值对。
containsKey(Object key):检查是否包含指定的键。
containsValue(Object value):检查是否包含指定的值。
size():返回 HashMap 中键值对的数量。
isEmpty():检查 HashMap 是否为空。
keySet():返回所有键的集合。
values():返回所有值的集合。
entrySet():返回 HashMap 中所有键值对的 Set 集合。
clear():清空所有元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import java.util.HashMap; import java.util.Map;
public class HashMapExample { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1); map.put("banana", 2); map.put("orange", 3);
System.out.println("Value for key 'apple': " + map.get("apple"));
System.out.println("Contains key 'banana': " + map.containsKey("banana"));
System.out.println("Contains value 2: " + map.containsValue(2));
map.remove("banana"); System.out.println("After removing 'banana': " + map);
System.out.println("Size of map: " + map.size());
System.out.println("Is map empty? " + map.isEmpty());
System.out.println("All keys: " + map.keySet());
System.out.println("All values: " + map.values());
for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }
map.clear(); System.out.println("After clearing map: " + map); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> mp = new HashMap<>(); for (int i = 0; i < nums.length; i++){ int temp = target - nums[i]; if (mp.containsKey(temp)){ return new int[]{mp.get(temp), i}; } mp.put(nums[i], i); } return new int[0]; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public int longestConsecutive(int[] nums) { Set<Integer> num_set = new HashSet<Integer>(); for (int num : nums){ num_set.add(num); }
int ans = 0; for (int num : num_set){ if (!num_set.contains(num - 1)){ int cur = num; int temp = 1;
while (num_set.contains(cur + 1)){ cur++; temp++; } ans = Math.max(ans, temp); } } return ans; } }
|