在java中搜索对象列表并增加该对象的变量的最有效方法
搜索对象列表并增加其变量之一的最有效方法是什么?另外 addData() 函数调用 10000 次,并且在此列表中最多有 30 个带有增量变量的 diff-diff 键。
谢谢,
public void addData(List<DataWise> wise ,String name)
{
if(wise!=null)
{
for (DataWise dataWise : wise) {
if(dataWise.getName().equals(name))
{
dataWise.setVisits(1);
return;
}
}
}
DataWise dataWise2=new DataWise(name,1);
wise.add(dataWise2);
}
public class DataWise
{
private String name;
private int visits;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVisits() {
return visits;
}
public void setVisits(int visits) {
this.visits+= visits;
}
}
What is the most efficient way to search a list of objects and also increment one of its variables? Also addData() function call 10000 time and in this list have max 30 diff-diff key with increment variable .
Thanks,
public void addData(List<DataWise> wise ,String name)
{
if(wise!=null)
{
for (DataWise dataWise : wise) {
if(dataWise.getName().equals(name))
{
dataWise.setVisits(1);
return;
}
}
}
DataWise dataWise2=new DataWise(name,1);
wise.add(dataWise2);
}
public class DataWise
{
private String name;
private int visits;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVisits() {
return visits;
}
public void setVisits(int visits) {
this.visits+= visits;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果保证每个 DataWise 的名称在列表中是唯一的,请使用
HashMap
,其中 String 键是 DataWise 的名称。这将导致 O(1) 而不是 O(n):请注意,setter (
setVisits()
) 应该将访问值设置为参数的值。增加访问次数确实是违反直觉的。这就是为什么我使用了incrementVisits方法,它更清晰。If it's guarantteed that the name of each DataWise is unique in the list, use a
HashMap<String, DataWise>
, where the String key is the name of the DataWise. This will lead to O(1) instead of O(n):Note that a setter (
setVisits()
) should set the visits value to the value of the argument. Incrementing the number of visits is really counter-intuitive. This is why I used anincrementVisits
method, which is much clearer.