Here is a utility method that converts a Collection of Integers to an array of ints. If the input is null, null is returned. If the input contains any null values, a defensive copy is created, stripping all null values from it. The original collection is left unchanged.
public static int[] toIntArray(final Collection data){
int[] result;
// null result for null input
if(data == null){
result = null;
// empty array for empty collection
} else if(data.isEmpty()){
result = new int[0];
} else{
final Collection effective;
// if data contains null make defensive copy
// and remove null values
if(data.contains(null)){
effective = new ArrayList(data);
while(effective.remove(null)){}
// otherwise use original collection
}else{
effective = data;
}
result = new int[effective.size()];
int offset = 0;
// store values
for(final Integer i : effective){
result[offset++] = i.intValue();
}
}
return result;
}
Update: Guava has a one-liner for this functionality:
int[] array = Ints.toArray(data);
Reference: