Best way to get value from Collection by index

前端 未结 10 1502
旧时难觅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:39

    Convert the collection into an array by using function

    Object[] toArray(Object[] a) 
    
    0 讨论(0)
  • 2020-12-05 17:40

    I agree that this is generally a bad idea. However, Commons Collections had a nice routine for getting the value by index if you really need to:

    CollectionUtils.get(collection, index)

    0 讨论(0)
  • 2020-12-05 17:43

    You must either wrap your collection in a list (new ArrayList(c)) or use c.toArray() since Collections have no notion of "index" or "order".

    0 讨论(0)
  • 2020-12-05 17:49

    I agree with Matthew Flaschen's answer and just wanted to show examples of the options for the case you cannot switch to List (because a library returns you a Collection):

    List list = new ArrayList(theCollection);
    list.get(5);
    

    Or

    Object[] list2 = theCollection.toArray();
    doSomethingWith(list[2]);
    

    If you know what generics is I can provide samples for that too.

    Edit: It's another question what the intent and semantics of the original collection is.

    0 讨论(0)
提交回复
热议问题