I try to write a function that accepts an arbitrary number of arguments such as:
public static void closeAllIfApproriate( final AutoCloseable... array ) throws SpecialException
{
try {
if( array == null)
return;
for( AutoCloseable value: array )
{
close(value);
}
} catch (SpecialExceptionhata) {
throw hata;
}
}
public static void close (final AutoCloseable value ) throws SpecialException
{
// Even if nothing happened, something definitely happened.
if(value != null)
value.close();
}
The function closeAllIfApproriate shall work properly for the sake of the other projects that depend upon it.
We know that array above will cause a heap allocation for an instance of this class. When I take a look at the way Google Guava is implemented, I have seen such sort of things:
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
}
// These go up to eleven. After that, you just get the varargs form, and
// whatever warnings might come along with it. :(
/**
* Returns an immutable list containing the given elements, in order.
*
* <p>The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 12}.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
@SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) {
checkArgument(
others.length <= Integer.MAX_VALUE - 12, "the total number of elements must fit in an int");
Object[] array = new Object[12 + others.length];
array[0] = e1;
array[1] = e2;
array[2] = e3;
array[3] = e4;
array[4] = e5;
array[5] = e6;
array[6] = e7;
array[7] = e8;
array[8] = e9;
array[9] = e10;
array[10] = e11;
array[11] = e12;
System.arraycopy(others, 0, array, 12, others.length);
return construct(array);
}
As you can see, Google engineers prefer to write of function for each number of parameters, rather than writing a single function such as:
public static <E> ImmutableList<E> of( E... parameters ) {
return construct(parameters);
}
Does the function above cause problems in the heap? What would be the intention of Google developers?
Thanks in advance.