fest-assert-2.x icon indicating copy to clipboard operation
fest-assert-2.x copied to clipboard

Varargs methods produce warnings for generic parameters

Open orionll opened this issue 12 years ago • 2 comments

List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
List<Integer> list3 = new ArrayList<Integer>();

List<List<Integer>> listOfLists = new ArrayList<List<Integer>>();
listOfLists.add(list1);
listOfLists.add(list2);
listOfLists.add(list3);

assertThat(listOfLists).contains(list1, list2, list3); // Type safety: A generic array of List<Integer> is created for a varargs parameter

This problem can be solved by overloading a varargs method with a different number of arguments:

public S contains(T value1) { ... }
public S contains(T value1, T value2) { ... }
public S contains(T value1, T value2, T value3) { ... }
public S contains(T value1, T value2, T value3, T value4) { ... }
...

This technique is used, for example, in Guava: http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/ImmutableList.java

orionll avatar Dec 12 '12 17:12 orionll

The problem is that the vararg takes an array of T, where it should just an array of Object. For tests it really doesn't matter type safety in the vararg. A failing test will tell the user that something is wrong.

alexruiz avatar Jan 10 '13 15:01 alexruiz

Wouldn't adding a @SafeVarargs annotation suffice?

mjball avatar Jul 29 '14 15:07 mjball