I am using IntelliJ IDEA with javac on JDK 1.8. I have the following code:
class Test
{
@SafeVarargs
final void varargsMe
In fact you should not write your code in this way. Consider the following example:
import java.util.*;
class Test
{
@SafeVarargs
@SuppressWarnings("varargs")
final void varargsMethod( Collection... varargs )
{
arrayMethod( varargs );
}
void arrayMethod( Collection[] args )
{
Object[] array = args;
array[1] = new Integer(1);
//
//ArrayList list = new ArrayList<>();
//list.add(new Integer(1));
//array[1] = list;
}
public static void main(String[] args)
{
ArrayList list1 = new ArrayList<>();
ArrayList list2 = new ArrayList<>();
(new Test()).varargsMethod(list1, list2);
}
}
If you run the code, you will see an ArrayStoreException because you put an Integer into a Collection
array.
However, if you replace array[1] = new Integer(1); with the three comment lines (i.e. to put an ArrayList
into the array), due to type erasure, no exception is thrown and no compilation error occurs.
You want to have a Collection
array, but now it contains a ArrayList
. This is quite dangerous as you won't realise there is a problem.