Java 在hashMap中存储信息时出现问题<;字符串,ArrayList<;字符串>&燃气轮机;
我在这个hashmap中存储数据时遇到了一个问题,我正在用Java编程 我的系统由一些聊天组成,在散列图中,我必须插入聊天作为索引和连接到特定聊天的用户列表,我的问题是散列图的初始化,因为我只需要输入聊天,但是ArrayList是空的,因为没有连接的用户,只是我不知道如何正确执行此操作 这是我的代码的一个小示例:Java 在hashMap中存储信息时出现问题<;字符串,ArrayList<;字符串>&燃气轮机;,java,Java,我在这个hashmap中存储数据时遇到了一个问题,我正在用Java编程 我的系统由一些聊天组成,在散列图中,我必须插入聊天作为索引和连接到特定聊天的用户列表,我的问题是散列图的初始化,因为我只需要输入聊天,但是ArrayList是空的,因为没有连接的用户,只是我不知道如何正确执行此操作 这是我的代码的一个小示例: public class Master { private HashMap<String, ArrayList<String>> chatBox;
public class Master {
private HashMap<String, ArrayList<String>> chatBox;
public Master() {
chatBox = new HashMap<String, ArrayList<String>>();
}
public insert() {
FileReader fr;
BufferedReader br;
try {
fr = new FileReader("listChat.txt");
br = new BufferedReader(fr);
while(true) {
String topic = br.readLine();
if(topic == null)
break;
chatBox.put(topic, null);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
公共类主控{
私有HashMap聊天盒;
公共硕士(){
chatBox=newhashmap();
}
公共插入(){
文件阅读器fr;
缓冲剂;
试一试{
fr=新文件阅读器(“listChat.txt”);
br=新的缓冲读取器(fr);
while(true){
字符串主题=br.readLine();
if(主题==null)
打破
chatBox.put(主题,空);
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
我建议您在hashmap中添加新元素时,通过创建空的ArrayList来更改代码:
while(true) {
String topic = br.readLine();
if(topic == null)
break;
chatBox.put(topic, new ArrayList<String>());
}
while(true){
字符串主题=br.readLine();
if(主题==null)
打破
put(主题,newarraylist());
}
当您必须使用消息更新此主题时,您将获得键“topic”的值并在ArrayList中添加新元素那么,具体问题是什么?null不是空的ArrayList。它根本不是ArrayList。空的ArrayList是使用
new ArrayList()创建的
。谢谢,就是那个错误,我在一杯水里迷了路。