I have such method:
public void show(Object o)
{
//show content of object
}
and I would like to pass to it TreeSet or HashMap. But its a different iteration, I mean, when I want to show a content of TreeSet, I use that code:
while ( iter.hasNext() )
{
System.out.println( iter.next());
}
but when I have a HasMap, I print it like this:
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
String value = map.get(key).toString();
System.out.println(key + " " + value);
}
Is there a way to show the content of a collection, when I dont know, if user pass a TreeSet or HashMap? I cant do any conversion in show method (thats not the point). Any ideas?
Not directly, but if your method is declared as:
public <T> void show(Iterable<T> iterable) {
for(T t: iterable) {
System.out.println(t);
}
}
then you can use it like this:
show(set);
show(map.entrySet());
Not exactly what you want, but Map and Set are inherently different and you can't really treat them the same way (polymorphically).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With