I have a method that is supposed to return an instance of a given collection class with the given entries. The implementation is shown below.
public static <E, C extends Collection<E>> C
initalizeAndAddToCollection(Class<C> clazz, E... entries) {
//Collection object
Collection<E> collection;
//try to invoke default constructor of C
try {
collection = clazz.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException |
InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException();
}
//Add elements to collection
for (E entry: entries)
collection.add(entry);
return (C) collection;
}
The problem is that the following code runs even though a double
should not be able to be stored in a list of type Integer
//Create and instantiate an ArrayList with element 1.0
ArrayList<Integer> list = initalizeAndAddToCollection(ArrayList.class, 1.0);
System.out.print(list.get(0));
Why does this code run, and how do I make it so that it results in either a compile or runtime error?
Edit: I noticed list.get(0).getClass()
does generate an exception, but I am not sure why either (or why the previous code does not).