A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 舒远 黑马帝   /  2012-9-18 22:33  /  2362 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public static void main(String[] args) throws Exception {
  2.         ArrayList<? extends Object> aList = new ArrayList<String>();//编译正常通过
  3.         aList.add(null);//只能存入null,其他任何数据都进不来。为什么只能存入null?
  4.         aList.add(null);
  5.         System.out.println(aList.size());//打印出来2
  6.         aList.remove(null);
  7.         System.out.println(aList.size());//aList中存在两个null,打印出来为1,为什么?
  8. }
复制代码

4 个回复

倒序浏览
public static void main(String[] args) throws Exception {

        ArrayList<? extends Object> aList = new ArrayList<String>();//编译正常通过

        aList.add(null);//只能存入null,其他任何数据都进不来。为什么只能存入null?  因为泛型的类型不知道 又因为是基础了Object 所以只能存入null

        aList.add(null);

        System.out.println(aList.size());//打印出来2

        aList.remove(null);

        System.out.println(aList.size());//aList中存在两个null,打印出来为1,为什么?为什么打印1 因为 aList.remove(null);移除了

}
回复 使用道具 举报
  1. public static void main(String[] args) throws Exception {

  2.         ArrayList<? extends Object> aList = new ArrayList<String>();//编译正常通过

  3.         aList.add(null);//只能存入null,其他任何数据都进不来。为什么只能存入null?

  4.         aList.add(null);

  5.         System.out.println(aList.size());//打印出来2

  6.         aList.remove(null);

  7.         System.out.println(aList.size());//aList中存在两个null,打印出来为1,为什么?

  8. }
复制代码
第一个问题:ArrayList<? extends Object> aList = new ArrayList<String>();//这样定义是不允许的 左右必须一致

第二个问题:可以查看API文档
aList.remove(null);
remove方法是移除此列表中首次出现的指定元素(如果存在)。所以是1  没有错!




回复 使用道具 举报
各位回帖的辛苦了!
但我还是不明白,第一个问题:为什么这样的集合中就只能存入null值,其他啥也存不了,真心不明白!。
第二个问题通过查文档已经明白了!
回复 使用道具 举报
我上网查了一下,貌似是这么个意思:
ArrayList<? extends Object> aList = new ArrayList<String>();
不可以向aList中添加任何元素,因为不能保证aList中真正保存什么类型的对象。aList中还可以保存Integer类型呢,所以aList中不能添加元素。
不能添加元素,要这玩意干啥呢?
是为了向外读数据,比如,一列表中充满了数据,从中向外读数据就是很有用的比如从List<Integer>列表中把数据读出来,复制到List<Number>中。下面是个小例子,
  1. Collection<Integer> aCol = new ArrayList<Integer>();
  2.                 aCol.add(1);
  3.                 aCol.add(2);
  4.                 aCol.add(3);

  5.                 List<? extends Number> srcList = new ArrayList<Integer>(aCol);
  6.                 System.out.println(srcList);// 这里输出[1,2,3]

  7.                 ArrayList<Number> destList = new ArrayList<Number>();
  8.                 destList.add(5);
  9.                 destList.add(6);
  10.                 destList.add(7);
  11.                 destList.add(8);

  12.                 Collections.copy(destList, srcList);
  13.                 System.out.println(destList);
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马