Reputation: 2912
I have created a HashSet class that extends HashSet in Java. If I just add one element the code is fine. But when I use addAll it states the following:
The method addAll(Collection<? extends Number>) in the type MyHashSet<Number> is not applicable for the arguments (Iterable<Integer>)
What is the reason and how can I come around it?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
public class MyHashSet<E> extends HashSet<E> {
private int count;
public int Count() {
return count;
}
@Override public boolean add(E e) {
count++;
return super.add(e);
}
@Override public boolean addAll(Collection<? extends E> c) {
count += c.size();
return super.addAll(c);
}
public static void main(String[] args) {
MyHashSet<Number> hs = new MyHashSet<>();
hs.add(new Integer(1));
Iterable<Integer> integers = new ArrayList<Integer>(Arrays.asList(1,3,5,7,9));
hs.addAll(integers);
}
}
Upvotes: 0
Views: 5001
Reputation: 200168
Declare integers
as
Collection<Integer> integers;
because addAll
does not support arbitrary Iterable
s. This is due to historical reasons, Iterable
is a retrofitted interface and the method signature could not be changed without breakage.
Upvotes: 5