Java annotation @SafeVarargs

Introduction

The @SafeVarargs annotation can designate certain methods and constructors that use a variable number of arguments as safe.

Methods can be passed with a variable number of arguments.

These arguments may be generics.

It may be desirable to suppress harmless warnings using the @SafeVarargs annotation.

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> a1 = new ArrayList<>();
    a1.add(1);//from   w  w w.java 2  s . c o m
    a1.add(2);
    ArrayList<Float> a2 = new ArrayList<>();
    a2.add(3.0F);
    a2.add(4.0F);
    displayElements(a1, a2, 12);
  }

  @SafeVarargs
  public static <T> void displayElements(T... array) {
    for (T element : array) {
      System.out.println(element.getClass().getName() + ": " + element);
    }
  }
}



PreviousNext

Related