【问题标题】:Create a generic method Print which will accept all type of collections to It创建一个通用方法 Print 它将接受所有类型的集合到它
【发布时间】:2021-05-27 22:55:56
【问题描述】:

为什么地图的打印方法不起作用? 该方法应该接受所有泛型并打印它们。 它适用于列表、集合、队列,但地图出现问题。

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 不是一个集合。
  • 您的print 方法也是不必要的。只需使用System.out.print(),它就可以正常工作。
  • 要打印课程内容,您只需在 bot 集合或地图上调用 toString() 方法,它就会打印您的内容。
  • 使用 Collection&lt;?&gt; 代替原始类型。由于Map 不是一个集合,你必须做出决定。您可以将m.entrySet() 传递给该方法。或使用keySet()values()

标签: java generics collections compiler-errors hashmap


【解决方案1】:

Map 不是Collection。您可以像这样调用print 方法:

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

重载如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多