Java examples for Collection Framework:Array Convert
Converts a list to a new copy of array based on the start index and end index.
//package com.java2s; import java.util.Collection; import java.util.List; import java.util.Map; public class Main { public static void main(String[] argv) { List list = java.util.Arrays.asList("asdf", "java2s.com"); System.out.println(java.util.Arrays.toString(toArray(list))); }//from ww w. jav a2 s .com /** * Converts a list to a new copy of array based on the start index and end index. * * @param list * @param startIndex * @param endIndex * @return */ @SuppressWarnings({ "unchecked", "cast" }) public static final <T> T[] toArray(List<T> list, int startIndex, int endIndex) { if (isEmpty(list)) { return (T[]) list.toArray(); } List<T> subList = list.subList(startIndex, endIndex); return (T[]) subList.toArray((T[]) java.lang.reflect.Array .newInstance(list.get(0).getClass(), subList.size())); } public static final <T> T[] toArray(List<T> list) { return toArray(list, 0, list.size()); } /** * This is a convenience method that returns true if the specified collection is null or empty * * @param <T> * Any type of object * @param collection * @return */ public static <T> boolean isEmpty(Collection<T> collection) { return collection == null || collection.isEmpty(); } /** * This is a convenience method that returns true if the specified map is null or empty * * @param <T> * any type of key * @param <U> * any type of value * @param map * @return */ public static <T, U> boolean isEmpty(Map<T, U> map) { return map == null || map.isEmpty(); } public static int size(Collection<? extends Object> collection) { if (collection == null) { return 0; } return collection.size(); } }