Miguel Carrasco
Miguel Carrasco

Reputation: 181

Casting a HashMap

i´m trying to make a casting of Hasmap

I have this hasmap:

 Map<String, Object> requestargs = new  Map<String, Object>();

Other side i have a method who bring me a hashmap of: Map<String, Document>

MultipartForm form = MgnlContext.getWebContext().getPostedForm();

The method is getDocuments();

I need to put the return of this method in my hashmap making something like this:

requestargs = form.getDocuments();

But i don´t know how to cast this Hasmap og (String,Document) to (String,Object)

Thanks

Upvotes: 0

Views: 1722

Answers (1)

Andy Turner
Andy Turner

Reputation: 140309

Unless you can use a wildcard

Map<String, ? extends Object> requestargs

You will need to copy the map into a new map:

requestargs = new HashMap<String, Object>(form.getDocuments());

The two types are not related directly. Were you able to make the assignment directly (or via casting) it would be possible to insert a value with non-Document type into the map, and that would be type-unsafe:

Map<String, Document> docs = form.getDocuments();
Map<String, Object> requestargs = docs;  // not actually allowed
requestargs.put("Foo", new Object());
for (Document doc : docs.values()) {
  // doc isn't necessarily a Document! ClassCastExceptions abound.
}

To prevent this problem happening, such an assignment is forbidden by the type system.

The wildcard works because it makes it impossible to call put on the map, since there is no way to know what types can be put into the map safely.

Upvotes: 1

Related Questions