hotohoto
hotohoto

Reputation: 487

Can I convert ArrayList<HashMap> type to List<Map> in Java?

Can I convert ArrayList<HashMap> type to List<Map> in Java? Otherwise, what is the official or recommended workaround?

I have two interfaces with two different but similar types - ArrayList<HashMap> and List<Map>, and I need to pass data from one interface to another.

Thanks in advance.

Upvotes: 2

Views: 209

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200296

You should be more specific in what you are asking. If you have a method with the signature

method1(List<Map> maps)

then you are not allowed to pass in a List<HashMap> (which includes ArrayList<HashMap>). If method1 only reads from the list (i.e., uses the list as a producer, then the proper signature should be

method1(List<? extends Map> maps)

Also note that here Map is used as a raw type, which is also inappropriate. You should better use

method1(List<? extends Map<?,?> maps)

Upvotes: 9

Eran
Eran

Reputation: 394136

I would change the interface that accepts/returns an ArrayList<HashMap> to accept/return a List<Map> instead. It is a better practice to use interface types.

Upvotes: 5

Related Questions