java如何用hashmap存储数组
时间: 2024-02-03 20:14:57 浏览: 20
在Java中,可以使用HashMap来存储数组。HashMap是一种键值对的数据结构,可以将一个值与一个键相关联。以下是一个示例代码,展示了如何使用HashMap来存储一个数组:
```java
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0; i<arr.length; i++) {
map.put(i, arr[i]);
}
System.out.println(map);
}
}
```
在上面的代码中,我们首先声明了一个整型数组arr,然后创建了一个HashMap对象map。接着,我们使用for循环将数组元素逐个存储到HashMap中,其中数组下标作为键,数组元素作为值。最后,我们使用System.out.println()方法输出了HashMap对象。
相关问题
用put和get以及hashmap存储数组中的元素的英文单词统计的JAVA的代码怎么写
以下是JAVA代码示例:
```java
import java.util.*;
public class WordCount {
public static void main(String[] args) {
String[] words = {"apple", "banana", "orange", "apple", "banana", "apple"};
HashMap<String, Integer> wordCounts = new HashMap<String, Integer>();
for (String word : words) {
if (wordCounts.containsKey(word)) {
int count = wordCounts.get(word);
wordCounts.put(word, count + 1);
} else {
wordCounts.put(word, 1);
}
}
for (Map.Entry<String, Integer> entry : wordCounts.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
```
这个程序使用一个字符串数组来存储单词,通过遍历数组,并且利用HashMap来统计单词出现的次数。
在程序中,我们首先创建一个空的HashMap对象wordCounts来存储单词以及它们出现的次数。然后我们遍历字符串数组中的每一个单词,如果该单词已经出现过,我们就从wordCounts对象中获取该单词的计数器,然后将计数器加1,并且存储回wordCounts中。如果该单词还没有出现过,我们就将其添加到wordCounts中,并且把计数器置为1。
最后,我们遍历wordCounts对象,输出每一个单词以及它的计数器。这个程序的输出结果为:
apple : 3
banana : 2
orange : 1
hashmap添加数组的方法
在 Java 中,可以使用 HashMap 来存储键值对,如果想要在 HashMap 中添加一个数组,可以将数组作为 value 存储在 HashMap 中。下面是一个示例代码:
```
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// 创建一个 HashMap 实例
HashMap<String, int[]> hashMap = new HashMap<>();
// 创建一个数组
int[] array = {1, 2, 3, 4, 5};
// 将数组作为 value 存储在 HashMap 中
hashMap.put("array", array);
// 获取数组
int[] resultArray = hashMap.get("array");
// 打印数组
for (int i : resultArray) {
System.out.print(i + " ");
}
}
}
```
运行结果为:1 2 3 4 5。