Thursday, January 5, 2017

Best Loop Idiom for special casing the last element

References: StackOverflow1 StackOverflow2

Very often it happens that you need to iterate through the elements of a list/array and treat the first/last element in a special way.

For example: if you have an array {"tom", "jerry", "dog"} and want to print in a comma separated fashion.

Normally I end up appending Comma (",") after each element and finally after the loop exits, I just delete the last element which is unnecessary comma.

Turns out there are few elegant way to achieve this. One of the way is:

Iterator itemIterator = Arrays.asList(items).iterator();
if (itemIterator.hasNext()) {
  // special-case first item.  in this case, no comma
  while (itemIterator.hasNext()) {
    // process the rest
  }
}

This method is in fact used by Joiner class in Google Collections.

Complexity of Arrays.asList(items)


My initial suspicion was on Arrays.asList() method. I thought that the complexity of this method was O(n).

However the time complexity of this method is actually O(1) because list is merely a wrapper around the array.

Java API Documentation: Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)






No comments:

Post a Comment