简体   繁体   中英

Iterate through List or get Object by index from List?

Ok, so for example I have class Arena and added them to list and I need to get Arena by one parameter. It is more efficient to iterate through every object or get them from list ? Which way is more efficient?

public Arena getArena(String param) {
    List<Arena> arenas = ...;
    for(Arena arena : arenas) {
        if(arena.getParameter().equals(param)) return arena;
    }
}

OR

public Arena getArena(String param) {
    List<Arena> arenas = ...;
    for(int i = 0; i < arenas.size(); i++) {
        if(arenas.get(i).getParameter().equals(param)) return arenas.get(i);
    }
}

It depends on whether the List implementation you are using has random access (for example ArrayList) or not (for example LinkedList).

If it doesn't have random access, the second option would be less efficient, since arenas.get(i) would require iterating from the start (or from the end) of the list to the requested index.

If it's a random access list, both options would have similar running times, but the first one looks much cleaner.

The best way in my opinion is if you se HashMap since you can get element at O(1). But you need to add areas to hash map instead of list.

See this example:

public Arena getArena(String param) {
    HashMap<String, Arena> arenasHash = ...;
    return arenasHash.get(param);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM