Java Reference
In-Depth Information
This mismatch between a reified array passing onreified (and onreifiable) paramet-
erized types to a method is at the heart of the unchecked warning when the method is
called.
InJava5,callingoneofthesemethodscausesacompile-timewarning;declaringsuch
a method doesn't result in a similar warning. Although the existence of such a varargs
method doesn't cause heap pollution, its existence contributes to heap pollution by of-
fering an easy way to cause heap pollution to occur. Furthermore, it influences heap
pollutionbyofferingthemethodtobecalled.Forthisreason,methoddeclarationsthat
contributetoheappollutiondeserveacompilerwarning,justasthiswarningisalready
present for method calls that cause heap pollution.
TheJava7compileroutputswarningsinbothlocations,and Listing3-58 presentsa
scenario that leads to these warnings.
Listing 3-58. Merging a variable umber of List s of String s
import java.util.ArrayList;
import java.util.List;
class SafeVarargsDemo
{
public static void main(String[] args)
{
List<String> list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
List<String> list2 = new ArrayList<>();
list2.add("C");
list2.add("D");
list2.add("E");
System.out.println(merge(list1, list2)); // Output:
[A, B, C, D, E]
}
//@SafeVarargs
static List<String> merge(List<String>... lists)
{
List<String> mergedLists = new ArrayList<>();
for (int i = 0; i < lists.length; i++)
 
Search WWH ::




Custom Search