Java上下限&下界通配符

编程入门 行业动态 更新时间:2024-10-16 02:31:17
本文介绍了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?

    更多推荐

    Java上下限&amp;下界通配符

    本文发布于:2023-11-30 17:04:02,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1650807.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:通配符   下界   下限   Java   amp

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!