Created
March 23, 2016 22:27
An example of a utility method that uses short-cuts for known types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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