Java: Get first item from a collection

后端 未结 12 1115
说谎
说谎 2020-11-29 17:08

If I have a collection, such as Collection strs, how can I get the first item out? I could just call an Iterator, take its first

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 17:13

    There is no such a thing as "first" item in a Collection because it is .. well simply a collection.

    From the Java doc's Collection.iterator() method:

    There are no guarantees concerning the order in which the elements are returned...

    So you can't.

    If you use another interface such as List, you can do the following:

    String first = strs.get(0);
    

    But directly from a Collection this is not possible.

提交回复
热议问题