Home >Java >javaTutorial >Why do I need to use @SafeVarargs in Java 9?

Why do I need to use @SafeVarargs in Java 9?

王林
王林forward
2023-09-11 23:53:02662browse

为什么在Java 9中需要使用@SafeVarargs?

The varargs feature has been introduced in Java to facilitate the creation of methods with a variable number of parameters without resorting to array types Parameters or overloaded versions of the same method.

Prior to Java 9 versions, there was a warning message if the vararg method was used with generics. Although not all methods produce heap pollution, the compiler displays a warning for all variadic methods used with generics. That's why the @SafeVarargs concept was added in Java 9 version to avoid these warnings. If we add this annotation, the compiler will stop these warnings.

We can use the following command to compile the code

<strong>javac -Xlint:unchecked SafeVarargsTest1.java</strong>

In the example below, the compiler displays 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 example below, we applied @ SafeVarargsbefore private methods. Therefore, it does not display 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>

The above is the detailed content of Why do I need to use @SafeVarargs in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete