Best way to get value from Collection by index

前端 未结 10 1558
旧时难觅i
旧时难觅i 2020-12-05 17:08

What is the best way to get value from java.util.Collection by index?

10条回答
  •  余生分开走
    2020-12-05 17:36

    you definitively want a List:

    The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based.

    Also

    Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a > list is typically preferable to indexing through it if the caller does not know the implementation.

    If you need the index in order to modify your collection you should note that List provides a special ListIterator that allow you to get the index:

    List names = Arrays.asList("Davide", "Francesco", "Angelocola");
    ListIterator i = names.listIterator();
    
    while (i.hasNext()) {
        System.out.format("[%d] %s\n", i.nextIndex(), i.next());
    }
    

提交回复
热议问题