Forum Stats

  • 3,770,099 Users
  • 2,253,066 Discussions
  • 7,875,313 Comments

Discussions

Get rid of the famous get(0) and get(list.size() -1)

User_PCUYR
User_PCUYR Member Posts: 1 Green Ribbon
edited Nov 1, 2021 2:45PM in Java APIs Discussions

Hello everybody.

After some use of the Collection API, i have a little idea to suggest for the manipulation of the lists.

I've encountered a lot of use-case where i need to get the first element (and maybe the last).

For now, the solution to get the first element in a list (object which implements the interface List) is the famous get(0) .. .. ..

I don't know for you but for me, with the fact that Java become more and more verbose, it gives me a lot of itches to write:

  • myList.get(0) to get the first element.
  • myList.get(myList.size - 1) to get the last element.

Today, for a better understanding of the logic, a better readability, how about having methods like:

  • myList.getFirst() for the first element.
  • myList.getLast() for the last element.

The advantage is not only on the meaning of the method but also to hide the unnecessary presence of the item's number (and by the way the compute of the last item's position).

I want to know your point of view about this idea.

Thanks.