向arraylist中添加键值对
时间: 2024-02-16 19:04:58 浏览: 177
在Java中,ArrayList是一种只能存储对象而不能存储原始类型的集合类型。如果您想要存储键值对,可以使用Java中的Map集合类型。其中,HashMap是一种常用的Map实现类。
以下是向HashMap中添加键值对的示例代码:
```
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 1);
map.put("key2", 2);
```
在上面的示例中,我们使用HashMap实现了一个String类型的键和Integer类型的值之间的映射。您可以像上面的示例一样使用put()方法添加键值对。
相关问题
java中List里面添加一个键值对
Java中的List是一个有序的集合,而键值对通常是通过Map来实现的。如果你想在List中添加一个键值对,可以将键值对封装成一个对象,然后将该对象添加到List中。
例如,你可以创建一个名为KeyValuePair的类,该类包含key和value两个属性:
```
public class KeyValuePair<K, V> {
private K key;
private V value;
public KeyValuePair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
```
然后,你可以创建一个List,并将键值对对象添加到其中:
```
List<KeyValuePair<String, Integer>> list = new ArrayList<>();
KeyValuePair<String, Integer> pair = new KeyValuePair<>("key", 123);
list.add(pair);
```
在这个例子中,我们创建了一个List,其中包含了一个KeyValuePair对象,该对象的key为"key",value为123。你可以根据需要修改KeyValuePair类来适应不同类型的key和value。
java中获取键值对集合
在Java中,如果你有一个HashMap实例,你可以通过以下几种方式获取其键值对的集合:
1. 使用`entrySet()`方法:这个方法返回一个`Set<Map.Entry<K, V>>`类型的集合,其中包含了HashMap中所有的键值对。每个`Map.Entry`是一个实现了`Map.Entry<K, V>`接口的对象,它封装了一个键和一个对应的值。
```java
HashMap<String, Integer> map = new HashMap<>();
// 添加一些键值对...
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
```
2. 使用`keySet()`方法:如果只想获取所有键,可以使用这个方法,返回的是`Set<K>`类型的集合。
```java
Set<String> keySet = map.keySet();
```
3. 使用`values()`方法:如果只想获取所有值,可以使用这个方法,返回的是`Collection<V>`类型的集合。
```java
List<Integer> values = new ArrayList<>(map.values());
```
注意,这些方法返回的都是视图(view),修改集合会影响到HashMap的内容。如果你需要复制一份集合,可以先转换成列表或其他数据结构再进行操作。
阅读全文
相关推荐
















