Skip to content

Instantly share code, notes, and snippets.

@cobratbq
Created March 23, 2016 22:27
An example of a utility method that uses short-cuts for known types.
public class CollectionUtils {
public static <E extends Object> E getLast(final Collection<E> col) {
if (col.isEmpty()) {
throw new IllegalArgumentException("cannot retrieve last element from empty collection");
}
if (col instanceof LinkedList) {
return ((LinkedList<E>) col).getLast();
} else if (col instanceof List) {
return ((List<E>) col).get(col.size() - 1);
} else {
// skip all but last element and return last element
final Iterator<E> it = col.iterator();
E last = null;
while (it.hasNext()) {
last = it.next();
}
return last;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment