문제

I'm trying to use a third party library that has a method signature like so:

testMethod(Iterable<HashMap<String,Date>>, String, String)

How can I pass an iterable to this method?

I wanted to do something like the following, but it fails:

HashMap<String,Date> items = new HashMap<String, Date>();
items.put("item1", new Date());
items.put("item2", new Date());

testMethod(items, "more", "data");
도움이 되었습니까?

해결책

You need to pass an Iterable or one of its subtypes, e.g., List, Set, etc. So, you can add the HashMap to a List, and pass it:

HashMap<String,Date> items = new HashMap<String, Date>();
items.put("item1", new Date());
items.put("item2", new Date());

List<HashMap<String, Date>> list = new ArrayList<HashMap<String, Date>>();
list.add(items);

testMethod(list, "more", "data");

Note that since the parameter type is Iterable<HashMap<String, Date>>, you can only pass - List<HashMap...> or Set<HashMap...>, etc. You cannot pass a List<Map..> in it.

다른 팁

You need to wrap your Map with some object which is Iterable. Using Arrays.asList(T... a) ought to work here.

HashMap<String,Date> items = new HashMap<String, Date>();
items.put("item1", new Date());
items.put("item2", new Date());

testMethod(Arrays.asList(list), "more", "data");`

You need to pass an Iterable to the method. It looks like HashMap does not implement the Iterable interface. You could either subclass Map and add the Iterable interface to your subclass, or pass in a list of your map's entries.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top