为什么我无法将Object类型的对象添加到List<?&gt ;?中? [英] Why can not I add an object of type Object into a List<?>?

查看:166
本文介绍了为什么我无法将Object类型的对象添加到List<?&gt ;?中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,一个 List<?> 被定义为某个特定的未知类型的列表 。因此无论这个 List 的参数类型是什么,它都应该扩展 Object ,因为在Java中你不能有任何类型不会扩展 Object 。那么为什么下面的代码没有被编译?它是如何违反 listObj

As far as I understand a List<?> is definds as a list of some specific , yet unknown type . So whatever is the parameter type of this List, it should be extending Object because in Java you can not have any type that doesn't extend Object. So why the following code doesn't get compiled ? How is it violating the the invariant of the listObj

    List<?> listObj = returnSomeList();
    listObj.add(new Object()); //Why does this not work ?


推荐答案

List<?> listObj 可以指向任何类型的List,可以存储不同类型的对象。

List<?> listObj can point to any type of List that can store different kind of objects.

你认为如果让它添加任何对象是安全的,例如

How do you think, would it be safe to let it add any objects if for example

List<?> listObj = new ArrayList<String>();
listObj.add(new Object());

这篇关于为什么我无法将Object类型的对象添加到List&lt;?&gt ;?中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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