Java: Get first item from a collection

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

    You can do a casting. For example, if exists one method with this definition, and you know that this method is returning a List:

    Collection getStrings();
    

    And after invoke it, you need the first element, you can do it like this:

    List listString = (List) getStrings();
    String firstElement = (listString.isEmpty() ? null : listString.get(0));
    

提交回复
热议问题