Java: Get first item from a collection

后端 未结 12 1135
说谎
说谎 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:23

    You could do this:

    String strz[] = strs.toArray(String[strs.size()]);
    String theFirstOne = strz[0];
    

    The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:

    If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

提交回复
热议问题