最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Java上下限&下界通配符

SEO心得admin88浏览0评论
本文介绍了Java上下限&下界通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在阅读java泛型,我遇到了一个有趣的查询。我的问题如下。

I was reading java generics, I came across an interesting query. My question is as follows.

  • 对于上限通配符

  • For an upper bounded wildcard public static void printList(List<? extends Number> list) { for (int i = 0; i < 10; i++) { list.add(i);// gives compilation error } }

  • 对于下界通配符

  • For a lower bounded wildcard

    public static void printList(List<? super Integer> list) { for (int i = 0; i < 10; i++) { list.add(i);// successfully compiles } }

  • 我对此感到困惑,因为查看Sun Oracle文档我理解代码应该编译为点1以及

    I am confused with this because looking at the Sun Oracle documentation I understand that the code should compile for point 1 as well

    上限通配符 下限通配符<

    Upper Bound Wildcard Lower Bound Wildcard

    推荐答案

    任何人都可以帮我理解吗? >这是因为当你使用上限时,你不能向集合添加元素,只能读取它们。

    This is because when you are using upper bound, you cannot add elements to collection, only read them.

    这意味着这些是一些法律赋值:

    this means that these are some of legal assignments:

    List<? extends Number> l = new ArrayList<Integer>(); List<? extends Number> l = new ArrayList<Double>();

    ,所以你不能保证当添加对象时,它将保存正确类型的对象。为了更好的解释,请按照: 如何我添加到List< ;? extends Number>数据结构?

    so you cannot guarantee that when adding object, it will hold correct types of objects. for better explatation please follow: How can I add to List<? extends Number> data structures?

    发布评论

    评论列表(0)

    1. 暂无评论