如何使用 Java ArrayList 提高性能 [英] How to increase the performance with Java ArrayList

查看:66
本文介绍了如何使用 Java ArrayList 提高性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个巨大的 ArrayList 和下面的代码

I'm using a huge ArrayList with the code bellow

public final List<MyClass> list = new ArrayList<>();

public void update(MyClass myClass) {
int i;
for (i=0; i < list.size(); i++) {
        if (myClass.foo(list.get(i))) {
            list.set(i, myClass);
            break;
        }    
    }    
    if (i == list.size()) {    
        list.add(myClass);    
    }    
}

列表非常大.在这种情况下,我还可以做些什么来提高性能?也许使用一些 Java 8 特性,替换 ArrayList 或类似的东西.

The list is extremely large. There is something else that I can do to increase the performance with this scenario? Maybe using some Java 8 feature, replacing ArrayList or something like that.

另一个与此列表相关的运行时间太长的代码是下面的代码:

Another code that is taking too long to run related this List is the code bellow:

public List<MyClass> something(Integer amount) {
list.sort((m1, m2) -> Double.compare(m2.getBar(), m1.getBar()));
return list.stream()
        .limit(amount)
        .collect(Collectors.toList());
}

欢迎任何帮助,谢谢大家

Any help is welcome, thank you all

推荐答案

似乎选择了ArrayList 不好.

It seems like the choice of the ArrayList is not good.

在第一种情况下,您尝试通过列表中的属性查找对象.要在列表中查找对象,您必须检查列表中的每个元素.列表越大,它就会越长.(使用 ArrayList 的最坏情况复杂度为 O(N))

In the first case, you attempt to find an object by his properties in the list. To find an object in the list, you have to check in each elements of your list. Bigger is the list, the longer it will be. (You have a worst case complexity of O(N) with ArrayList)

如果您使用 HashMap 而不是 List,您可以使用您的属性作为地图的键.像这样,您可以直接选择需要更新的对象,而无需检查列表中的每个元素.执行时间将不再依赖于条目的数量.(使用 HashMap 的最坏情况复杂度为 O(1))

If you use an HashMap instead of a List, you can use your property as key of your map. Like this, you can select the object you need to update directly without check each element of your list. The execution time will be no more dependent of the number of entries. (You have a worst case complexity of O(1) with HashMap)

如果您使用 HashMap 而不是 ArrayList,您的更新代码将如下所示:

If you use HashMap instead of ArrayList, your update code gonna look like this:

public void update(MyClass myClass) {
    map.put(myClass.getKey(), myClass);
}

(其中 getKey() 是您尝试在 foo 方法中等于的属性).

(where getKey() is the properties you try to equals in your foo method).

但这仅适用于第一种情况.根据我们掌握的信息,这似乎是最好的解决方案.

But this is only for the first case. With the informations we have it seems the best solution.

这篇关于如何使用 Java ArrayList 提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆