简体   繁体   English

创建一个通用方法 Print,它将接受所有类型的 collections 到它

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

Why the print method for map is not working?为什么 map 的打印方法不起作用? the method should accept all generics and print them.该方法应该接受所有 generics 并打印它们。 it works fine for list, set, Queues but problem arises in map.它适用于列表、集合、队列,但问题出现在 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{
    
}

Map is not a Collection . Map不是Collection You can either call your print method like this:您可以像这样调用print方法:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM