List中的element可以为null?--是的

ArrayList中的源码

/**
 * Appends the specified element to the end of this list.
 *
 * @param e element to be appended to this list
 * @return <tt>true</tt> (as specified by {@link Collection#add})
 */
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

 

 

LinkedList中的源码

 

/**
 * Inserts the specified element at the specified position in this list.
 * Shifts the element currently at that position (if any) and any
 * subsequent elements to the right (adds one to their indices).
 *
 * @param index index at which the specified element is to be inserted
 * @param element element to be inserted
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public void add(int index, E element) {
    checkPositionIndex(index);

    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}

验证:

static class Data {
    String mName;
    public Data(String s) {
        this.mName = s;
    }

    @Override
    public String toString() {
        return "Data:" + mName;
    }
}

public static void main(String[] args) {
    List<Data> dataList = new ArrayList<>();
    dataList.add(null);
    dataList.add(new Data("shit"));
    System.out.println(dataList.size()); // 这里输出的是2

    for (Data d : dataList) {
        System.out.println(d.mName); // 这里会空指针异常
    }
}

参考资料
关于为什么ArrayList允许添加null https://softwareengineering.stackexchange.com/questions/163489/why-does-java-util-arraylist-allow-to-add-null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值