Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
<strong>javac -Xlint:unchecked SafeVarargsTest1.java</strong>
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.<strong>varargsMethod</strong>(<strong>Arrays.asList</strong>("Adithya", "Jaidev"), Arrays.asList("Raja", "Chaitanya"));
}
private void varargsMethod(<strong>List<String></strong>... list) {
for(List list1: list)
System.out.println(list1);
}
}
Output
<strong>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</strong>
<strong>[Adithya, Jaidev]
[Raja, Chaitanya]</strong>
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.<strong>varargsMethod</strong>(Arrays.asList("Adithya", "Jaidev"), Arrays.asList("Raja", "Chaitanya"));
}
<strong>@SafeVarargs</strong>
private void varargsMethod(<strong>List<String></strong>... list) {
for(List list1: list)
System.out.println(list1);
}
}
Output
<strong>[Adithya, Jaidev] [Raja, Chaitanya]</strong>
