001/** 002 * Copyright 2014 Tampere University of Technology, Pori Department 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package core.tut.pori.utils; 017 018import java.util.ArrayList; 019import java.util.Collection; 020import java.util.List; 021 022import org.apache.commons.lang3.ArrayUtils; 023import org.apache.log4j.Logger; 024 025/** 026 * 027 * Utility class for List utils 028 */ 029public final class ListUtils { 030 private static final Logger LOGGER = Logger.getLogger(ListUtils.class); 031 /** 032 * 033 */ 034 private ListUtils(){ 035 // nothing needed 036 } 037 038 /** 039 * Create a new list with n copies of new instances of the given class 040 * 041 * @param n 042 * @param cls 043 * @return new list or null if n < 1 or cls == null 044 * @throws IllegalArgumentException if the classes cannot be instantiated 045 */ 046 public static <T> List<T> createList(int n, Class<T> cls){ 047 if(n < 1 || cls == null){ 048 return null; 049 } 050 List<T> list = new ArrayList<>(n); 051 try { 052 for(int i=0;i<n;++i){ 053 list.add(cls.newInstance()); 054 } 055 } catch (InstantiationException | IllegalAccessException ex) { 056 LOGGER.error(ex, ex); 057 throw new IllegalArgumentException("Could not create instance of "+cls.toString()); 058 } 059 return list; 060 } 061 062 /** 063 * 064 * @param items 065 * @return true if items is null or empty 066 */ 067 public static boolean isEmpty(Collection<?> items){ 068 return (items == null || items.isEmpty()); 069 } 070 071 /** 072 * 073 * @param values 074 * @return new list or null if null or empty array was passed 075 */ 076 public static List<Integer> createList(int[] values){ 077 if(ArrayUtils.isEmpty(values)){ 078 return null; 079 } 080 List<Integer> iValues = new ArrayList<>(values.length); 081 for(int i=0;i<values.length;++i){ 082 iValues.add(Integer.valueOf(values[i])); 083 } 084 return iValues; 085 } 086}