我想将某个变量的所有值和每个值的频率存储在数据集中。为此,我使用 ArrayList<String>
存储值和 ArrayList<Integer>
存储频率(因为我不能使用 int
)。不同值的数量未知,这就是我使用 ArrayList
的原因而不是 Array
.
示例(简化)数据集:
a,b,c,d,b,d,a,c,b
ArrayList<String>
值看起来像:{a,b,c,d}
和 ArrayList<Integer>
频率看起来像:{2,3,2,2}
.
填写这些ArrayLists
我使用以下代码迭代数据集中的每条记录。
public void addObservation(String obs){
if(values.size() == 0){// first value
values.add(obs);
frequencies.add(new Integer(1));
return;//added
}else{
for(int i = 0; i<values.size();i++){
if(values.get(i).equals(obs)){
frequencies.set(i, new Integer((int)frequencies.get(i)+1));
return;//added
}
}
// only gets here if value of obs is not found
values.add(obs);
frequencies.add(new Integer(1));
}
}
但是,由于我将使用它的数据集可能非常大,我想优化我的代码,并使用 frequencies.set(i, new Integer((int)frequencies.get(i)+1));
看起来效率不是很高。
这引出了我的问题;如何优化 Integer
的更新ArrayList
中的值?
最佳答案
像这样创建HashMap
HashMap<String,Integer> hm = new HashMap<String,Integer>();
那么您的 addObservation 方法将如下所示
public void addObservation(String obs) {
if( hm.contains(obs) )
hm.put( obs, hm.get(obs)+1 );
else
hm.put( obs, 1 );
}
关于java - 如何优化 ArrayList<Integer> 中值的更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7594699/