Search code examples
javagenericscollectionscompiler-errorshashmap

Create a generic method Print which will accept all type of collections to It


Why the print method for map is not working? the method should accept all generics and print them. it works fine for list, set, Queues but problem arises in map.

public class Question6 {

    @SuppressWarnings("unchecked")
    static void print(@SuppressWarnings("rawtypes") Collection c) {
        System.out.println(c.getClass());
        c.forEach(System.out::println);
        System.out.println();
    }
    
    public static void main(String[] args) {
        List<Integer> l = new ArrayList<>();
        l.add(1);
        l.add(2);
        print(l);
            
        List<Dummy> ld = new ArrayList<Dummy>();
        ld.add(new Dummy());
        print(ld);

        Map<Integer,Integer> m = new LinkedHashMap<Integer, Integer>();
        m.put(1,1);
        print(m); // gives error?
                
    }
}

class Dummy{
    
}

Solution

  • Map is not a Collection. You can either call your print method like this:

    print(map.entrySet());
    // or 
    print(map.keys());
    // or
    print(map.values());
    

    or overload it as follows:

    static void print(Collection<?> c) {
        System.out.println(c.getClass());
        c.forEach(System.out::println);
        System.out.println();
    }
    
    static void print(Map<?, ?> map) {
        System.out.println(map.getClass());
        map.entrySet().forEach(System.out::println);
        System.out.println();
    }