Java tutorial
//package com.java2s; import java.util.*; public class Main { public static <T, C extends Collection<T>> C getElements(C c, int offset, int size) { if (c == null) { return null; } else if (c.isEmpty() || offset >= c.size() || size <= 0) { return newCollection(c); } if (offset < 0) { offset = Math.max(0, c.size() + offset); } if (offset + size > c.size()) { size = c.size() - offset; } C result = newCollection(c); if (c instanceof List) { result.addAll(((List<T>) c).subList(offset, offset + size)); } else { for (int i = offset; i < offset + size; i++) { result.add(getElement(c, i)); } } return result; } public static boolean isEmpty(Collection<?> collection) { return (collection == null || collection.isEmpty()); } public static int size(Collection<?> collection) { return (collection == null ? 0 : collection.size()); } public static int size(Collection<?>... collections) { int size = 0; if (collections != null) { for (Collection<?> c : collections) { if (c != null) { size += c.size(); } } } return size; } @SuppressWarnings("unchecked") public static <C extends Collection<?>> C newCollection(Object reference) { Class<?> clazz = null; if (reference instanceof Collection<?>) { clazz = (Class<?>) reference.getClass(); } else if (reference instanceof Class<?> && Collection.class.isAssignableFrom((Class<?>) reference)) { clazz = (Class<?>) reference; if (clazz.equals(List.class)) { clazz = (Class<?>) ArrayList.class; } else if (clazz.equals(Set.class)) { clazz = (Class<?>) LinkedHashSet.class; } } if (clazz != null) { try { return (C) clazz.newInstance(); } catch (Exception e) { } } return null; } public static <T> T getElement(Collection<T> c, int index) { return getElement(c, index, null); } public static <T> T getElement(Collection<T> c, int index, T defElement) { if (isEmpty(c) || index >= c.size()) { return defElement; } if (index < 0) { index = c.size() + index; if (index < 0) { return defElement; } } if (c instanceof List) { return ((List<T>) c).get(index); } else { for (T element : c) { if (index-- == 0) { return element; } } // unreachable return defElement; } } }