vendredi 10 mai 2019

Why does this method allow a double to be stored in ArrayList of type Integer?

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 <EntryType, CollectionType extends Collection<EntryType>> CollectionType initalizeAndAddToCollection(Class<CollectionType> collectionsClass, EntryType... entries) {
    //Collection object
    Collection<EntryType> collection;
    //try to invoke default contructor of CollectionType
    try {
        collection = collectionsClass.getDeclaredConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new RuntimeException();
    }
    //Add elements to collection
    for (EntryType entry: entries)
        collection.add(entry);
    return (CollectionType) 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 so that it results in either a compile or runtime error?





Aucun commentaire:

Enregistrer un commentaire