views:

254

answers:

6

Hi. I'm trying to learn java better and I got one question.

Say I got two collections, an ArrayList and a LinkedHashSet. Is it possible to make a function like this:

void print(collection c) {
    for (object tmp:c) {
        System.out.println(tmp);
    }
}
+3  A: 

Watch your capitalization:

private void printCollection(Collection collection) {

   for (Object obj : collection) {
      System.out.println(obj);
   }
}
Jason Nichols
Should be `for(Object obj : c)`
Felix Kling
Seconds too late. Should be `Collection<?>`, and `element` or `e` instead of `obj`.
Tom Hawtin - tackline
Make sure you implement the toString() method
Brendan
+2  A: 

Yes. ArrayList and LinkedHashSet are both Collections. The method that you wrote accepts a Collection (note the capital C) so it will accept any type of collection. This is referred to as polymorphism.

Vincent Ramdhanie
A: 

basically you just need ot use the iterator:

void print(collection c) 
{ 
    for (object tmp:c.iterator()) 
    { 
        System.out.println(tmp); 
    } 
} 
John Gardner
In Java, iterators are not iterable. You can only use for-each on iterables, not iterators.
Chris Jester-Young
ack, true. but who was the genious who decided that? :)
John Gardner
+1  A: 

It is possible, as both types implement Collection<E>. The convention is for class types in Java to start with a capital letter. Since 1.5, Java has used generics for its collections and you should use them in all new code. Since you're using the 1.5 style for loop, you should write generic code.

It's usually better to make functions operate on the least specific type as possible, as this gives the widest reuse. In this case, you only need something wich could go one up from Collection<T> to Iterable<T>, as you only need something which will work with the for loop. So combining generics and least power gives:

public class PrintLinePrinter {
    public <T> void print (Iterable<T> collection) { 
        for (T item : collection) {
            System.out.println(item); 
        }
    } 
} 
Pete Kirkham
A: 

System.out.println(Collection c) already print any type of collection in readable format. But if collection contains user defined objects , then you need to implement toString() in user defined class.

Shekhar
+1  A: 

'Loop free' solution:

void print(collection c) {
    System.out.println( Arrays.toString(c.toArray())); }
卢声远 Shengyuan Lu