I am receiving a large number of arraylists of objects that extend my object. I want to insert them into a hashmap for faster referencing. I decided to create a method to avoid duplicate code since it happens so often, and just for fun I want to be extra fancy and use generics. There are a few ways I know to do this, but none seem very clean or pretty; I'm wondering if I'm missing an easier solution. So I want to do something like this...
private void addToMap(Collections<? extends myObject> collection, Map<String, ? extends myObject> map){
for(MyObject myObject: collection){
map.put(myObject.getName(), myObject);
}
}
The contract of the method would require that the collection provided stores the same class as map does. I'm fine if the method throws an exception were someone to break that contract and try passing in two a collection that stored a different implementation of myObject then the map stored.
The code above fails, because I can't put 'myObject' into a collection expecting "? extends MyObject" to encourage type safety. I'm fine just casting it, but they only way I know to figure out how to cast it involves a few steps of ugly reflection and seems convoluted. I could also create some sort of inner class to have more powerful generics available to me (to force collection and map to store the same type) but it also feels like overkill.
So, is there a simple or pretty manner to creating this method in the most intuitive-to-the-reader manner possible? I know I could toss out the generics entirely and just cast everything from object, I'm just trying to figure out a more elegant method.