Question

Here is a code authored by Josh bloch, ( Linkedlist.java)

 * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.prev;
        }

Here I dont see any null ptr check for Collection c. On contrary effective java very much stresses on parameter validation, emphasizing null pointer check. If an invalid parameter value is passed to a method and the method checks its parameters before execution, it will fail quickly and cleanly with an appropriate exception.

I need to know what I am missing ? In other words why did he not do a null check for addAll function ?

Was it helpful?

Solution

Because Object[] a = c.toArray(); will throw the stated exception anyway, if c is null.

OTHER TIPS

Object[] a = c.toArray(); will obviously throw the NPE. What I would do in this case, would either check at the beginning if the param is null, and then return false (so it doesn't break the runtime flow - Objective-C style), OR assertIsNotNull at the beginning of the method, and specify it in the javadoc (e.g. "the thing must not be null, yo").

But that's just me. That's why APIs must always be well documented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top