Java上下限&下界通配符 [英] Java Generics for Upper bound & lower bound wild cards

查看:311
本文介绍了Java上下限&下界通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


  1. 对于上限通配符

  1. 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;下界通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆