Why @SafeVarargs is required in Java 9?


The varargs functionality has been introduced in Java to facilitate the creation of methods with a variable number of arguments without resorting to array-type parameters or overloaded versions of the same method.

Before Java 9 versions, if vararg methods are used with generics, then there is a warning message. Even though not all methods create heap pollution, compiler shows warning for all vararg methods used with generics. That's the reason @SafeVarargs concept was added to Java 9 version to avoid these warnings. If we added this annotation, then the compiler stops these warnings.

We can compile the code by using the below command

javac -Xlint:unchecked SafeVarargsTest1.java

In the below example, the compiler shows a warning message to the user.

Example

import java.util.Arrays;
import java.util.List;

public class SafeVarargsTest1 {
   public static void main(String args[]) {
      SafeVarargsTest1 test = new SafeVarargsTest1();
      test.varargsMethod(Arrays.asList("Adithya", "Jaidev"), Arrays.asList("Raja", "Chaitanya"));
   }
   private void varargsMethod(List<String>... list) {
      for(List list1: list)
         System.out.println(list1);
   }
}

Output

SafeVarargsTest.java:7: warning: [unchecked] unchecked generic array creation for varargs parameter of type List[]
test.varargsMethod(Arrays.asList("Adithya", "Jaidev"), Arrays.asList("Raja", "Chaitanya"));
^
SafeVarargsTest.java:9: warning: [unchecked] Possible heap pollution from parameterized vararg type List
private void varargsMethod(List... list) {
^
2 warnings

[Adithya, Jaidev]
[Raja, Chaitanya]


In the below example, we have applied @SafeVarargs before the private method. So, it doesn't show any warning message.

Example

import java.util.Arrays;
import java.util.List;

public class SafeVarargsTest2 {
   public static void main(String args[]) {
      SafeVarargsTest2 test = new SafeVarargsTest2();
      test.varargsMethod(Arrays.asList("Adithya", "Jaidev"), Arrays.asList("Raja", "Chaitanya"));
   }
   @SafeVarargs
   private void varargsMethod(List<String>... list) {
      for(List list1: list)
         System.out.println(list1);
   }
}

Output

[Adithya, Jaidev]
[Raja, Chaitanya]

Updated on: 24-Mar-2020

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements