java arrlist存入hashtable
时间: 2023-11-07 19:05:12 浏览: 46
Java中的ArrayList和Hashtable都是集合类,可以存储一组对象。如果要将ArrayList中的对象存储到Hashtable中,可以使用循环遍历ArrayList中的每个对象,并将其作为值放入Hashtable中,同时指定一个键来标识该值。
下面是一个示例代码,将ArrayList中的字符串存储到Hashtable中,键为字符串的第一个字符:
```
import java.util.ArrayList;
import java.util.Hashtable;
public class ArrayListToHashtable {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("cat");
Hashtable<Character, String> table = new Hashtable<Character, String>();
for (String str : list) {
table.put(str.charAt(0), str);
}
System.out.println(table);
}
}
```
运行结果为:
```
{a=apple, c=cat, b=banana}
```
可以看到,ArrayList中的每个字符串被存储到了Hashtable中,并按照第一个字符作为键进行了标识。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)