HashMap
1.HashMap介绍:
-
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).(创建一个默认初始化容量为16,默认加载因子为0.75的空散列表)
- 容量是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度
-
HashMap的继承关系
package java.util; import java.io.*; public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable{ }
HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。
- 实现不同步,线程不安全
2.HashMap用法:
- HashMap构造函数:
// 默认构造函数。 HashMap() // 指定“容量大小”的构造函数 HashMap(int capacity) // 指定“容量大小”和“加载因子”的构造函数 HashMap(int capacity, float loadFactor) // 包含“子Map”的构造函数 HashMap(Map<? extends K, ? extends V> map)
- HashMap接口:
void clear() Object clone() boolean containsKey(Object key) boolean containsValue(Object value) Set<Entry<K, V>> entrySet() V get(Object key) boolean isEmpty() Set<K> keySet() V put(K key, V value) void putAll(Map<? extends K, ? extends V> map) V remove(Object key) int size() Collection<V> values()
3.LeetCode相关题目:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
4.参考代码:
public class TwoSum {
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; map.put(numbers[i], ++i))
if (map.containsKey(target - numbers[i]))
return new int[]{map.get(target - numbers[i]),i+1};
return new int[]{0,0};
}
}
上一篇: Linux 安装subversion
下一篇: hashmap