HashMap<K,V>
10 methodsMap 接口的哈希表实现。允许 null 键和值。
boolean add(E e)将 value 与 key 关联。返回之前的值(或 null)。
Parameters
| Name | Type | Description |
|---|---|---|
| key | E | 键。 |
Returns
boolean
Example
java
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
// list == ["a", "b"]E get(int index)返回 key 映射到的值,不存在则返回 null。
Parameters
| Name | Type | Description |
|---|---|---|
| key | int | 要查找的键。 |
Returns
E
Example
java
List<String> list = List.of("a", "b", "c");
list.get(0) // "a"
list.get(2) // "c"E set(int index, E element)移除 key 的映射。返回之前的值(或 null)。
Parameters
| Name | Type | Description |
|---|---|---|
| key | int | 要移除的键。 |
| element | E | New element. |
Returns
E
Example
java
List<String> list = new ArrayList<>(List.of("a", "b"));
String old = list.set(0, "x");
// old == "a", list == ["x", "b"]E remove(int index)如果映射包含指定键的映射关系则返回 true。
Parameters
| Name | Type | Description |
|---|---|---|
| key | int | 要检查的键。 |
Returns
E
Example
java
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
String r = list.remove(1);
// r == "b", list == ["a", "c"]int size()如果映射将一个或多个键映射到指定值则返回 true。
Returns
int
Example
java
List<Integer> list = List.of(1, 2, 3);
list.size() // 3boolean isEmpty()返回映射中包含的键的 Set 视图。
Returns
boolean
Example
java
new ArrayList<>().isEmpty() // true
List.of(1).isEmpty() // falseboolean contains(Object o)返回映射中包含的值的 Collection 视图。
Parameters
| Name | Type | Description |
|---|---|---|
| o | Object | Element to find. |
Returns
boolean
Example
java
List<String> list = List.of("a", "b");
list.contains("a") // true
list.contains("z") // falseint indexOf(Object o)返回映射中包含的映射关系的 Set 视图。
Parameters
| Name | Type | Description |
|---|---|---|
| o | Object | Element to find. |
Returns
int
Example
java
List<String> list = List.of("a", "b", "a");
list.indexOf("a") // 0
list.indexOf("z") // -1void clear()返回映射中键值映射的数量。
Returns
void
Example
java
List<String> list = new ArrayList<>(List.of("a", "b"));
list.clear();
// list == []Object[] toArray()如果映射不包含任何键值映射则返回 true。
Returns
Object[]
Example
java
List<String> list = List.of("a", "b");
Object[] arr = list.toArray();
// arr == ["a", "b"]
String[] sa = list.toArray(new String[0]); // typed version