Java 使用arraylist散列映射并从中创建新的arraylist
我试图清理我的代码,并希望在代码中使用优化的方法 目前我有这种类型的hashmapJava 使用arraylist散列映射并从中创建新的arraylist,java,arraylist,hashmap,Java,Arraylist,Hashmap,我试图清理我的代码,并希望在代码中使用优化的方法 目前我有这种类型的hashmap 私有HashMap fData 所以数据每5秒钟就来自服务器。我每5秒钟更新一次hashmap,就像这样 fData.put("Student", allStudent); fData.put("Emp", allEmp); fData.put("Other", allOther); 因此,从allproperty类对象中,有标记字段,我试图为所有键提取该标记字段,并创
私有HashMap fData代码>
所以数据每5秒钟就来自服务器。我每5秒钟更新一次hashmap,就像这样
fData.put("Student", allStudent);
fData.put("Emp", allEmp);
fData.put("Other", allOther);
因此,从allproperty类对象中,有标记字段,我试图为所有键提取该标记字段,并创建integer的新arraylist,以便每隔5秒在创建的arraylist中追加标记
我以前为每个学生、emp和其他人使用了不同的arraylist,它工作得很好,但似乎有很多代码重复。这就是为什么我要用哈希映射来实现它
我尝试这样做,但它不是附加数据
for (String type: allTypes) {
if(fData.get(type).size() > 0){
arraySort(fData.get(type));
temp = new ArrayList<Integer>();
temp.add(fData.get(type).get(0).marks);
}
cData.put(type, temp);
在最后,我想要三个新的arraylist和键,并能够在每5秒钟追加数据。谢谢
获取您的ArrayList
2a。如果不存在,请将您的新ArrayList
2b。否则请使用此ArrayList
。它是可变的。因此,您可以在此对象上调用.add
,它将在HashMap
试试这个:
for (String type: allTypes) {
if (fData.get(type).size() > 0) {
arraySort(fData.get(type));
if (cData.get(type) == null) {
temp = new ArrayList<Integer>();
temp.add(fData.get(type).get(0).marks);
cData.put(type, temp);
} else {
cData.get(type).add(fData.get(type).get(0).marks);
}
}
}
for(字符串类型:allTypes){
if(fData.get(type).size()>0){
arraySort(fData.get(type));
if(cData.get(type)==null){
temp=新的ArrayList();
临时添加(fData.get(type).get(0).marks);
cData.put(类型、温度);
}否则{
cData.get(type).add(fData.get(type).get(0).marks);
}
}
}
类allProperty应具有作为公共字段的标记…是的,它具有…我可以访问它..我知道这一点。您确定对temp使用“addAll”不会更好吗?不清楚fData
和标记的类型是什么。请尝试在日志fData.get(type).get(0)中打印此项。标记是否正确获取数据?它应该给出int。。由于temp是arraylist,所以它会得到,但问题是,当我在5秒后获得新数据时,它不会附加到新创建的arraylist中。我希望我很清楚,但我想我也在做同样的事情……想法是更新每个特定于keyYou creatingnew arraylist
的arraylist,而不是在代码中使用旧的arraylist。当您使用旧的方法时,您不应该调用map.put(),但如果我不创建新的方法,那么循环将运行三次,并为特定的键添加三个值,而不是一个值。这是错误…因为不存在对象试图调用虚拟方法“boolean java.util.ArrayList.add(java.lang.object)”'在空对象引用上,而不是!=空
signalTypes.add("Student");
signalTypes.add("Emp");
signalTypes.add("Other");
for (String type: allTypes) {
if (fData.get(type).size() > 0) {
arraySort(fData.get(type));
if (cData.get(type) == null) {
temp = new ArrayList<Integer>();
temp.add(fData.get(type).get(0).marks);
cData.put(type, temp);
} else {
cData.get(type).add(fData.get(type).get(0).marks);
}
}
}