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