Author: tchemit Date: 2012-10-28 12:57:35 +0100 (Sun, 28 Oct 2012) New Revision: 2429 Url: http://nuiton.org/repositories/revision/nuiton-utils/2429 Log: fixes #2386: Add get method in CollectionUtil Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/CollectionUtil.java Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/CollectionUtil.java =================================================================== --- trunk/nuiton-utils/src/main/java/org/nuiton/util/CollectionUtil.java 2012-10-26 11:43:54 UTC (rev 2428) +++ trunk/nuiton-utils/src/main/java/org/nuiton/util/CollectionUtil.java 2012-10-28 11:57:35 UTC (rev 2429) @@ -164,6 +164,55 @@ } return (Set<O>) list; } + + /** + * Get data at given {@code index} from the given collection. + * + * @param collection the collection to scan + * @param index index to seek + * @param <T> type of data in collection + * @return the data found at given index + * @throws IndexOutOfBoundsException if there is such index in collection + * @since 2.6.4 + */ + public static <T> T get(Collection<T> collection, int index) throws IndexOutOfBoundsException { + T result = null; + if (collection != null) { + int i = 0; + for (T t : collection) { + if (index == i) { + result = t; + break; + } + i++; + } + if (i != index) { + throw new IndexOutOfBoundsException("No element at index " + index); + } + } + return result; + } + + /** + * Get data at given {@code index} from the given list. + * + * @param list the list to scan + * @param index index to seek + * @param <T> type of data in collection + * @return the data found at given index + * @throws IndexOutOfBoundsException if there is such index in list + * @since 2.6.4 + */ + public static <T> T get(List<T> list, int index) throws IndexOutOfBoundsException { + T result = null; + if (list != null) { + if (index < list.size()) { + throw new IndexOutOfBoundsException("No element at index " + index); + } + result = list.get(index); + } + return result; + } }
participants (1)
-
tchemit@users.nuiton.org