java warning: Varargs method could cause heap pollution from non-reifiable varargs parameter

前端 未结 5 1639
灰色年华
灰色年华 2021-01-17 17:32

I am using IntelliJ IDEA with javac on JDK 1.8. I have the following code:

class Test
{
    @SafeVarargs
    final void varargsMe         


        
5条回答
  •  伪装坚强ぢ
    2021-01-17 18:28

    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.

提交回复
热议问题