Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Varargs methods produce warnings for generic parameters #132

Open
orionll opened this issue Dec 12, 2012 · 2 comments
Open

Varargs methods produce warnings for generic parameters #132

orionll opened this issue Dec 12, 2012 · 2 comments
Assignees

Comments

@orionll
Copy link

orionll commented Dec 12, 2012

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

@alexruiz
Copy link
Owner

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.

@ghost ghost assigned alexruiz Jan 10, 2013
@mjball
Copy link

mjball commented Jul 29, 2014

Wouldn't adding a @SafeVarargs annotation suffice?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants