I encode some validators for the REST service that parse JSON, and I found out something audible for me (I'm not a JAVA expert at all
)
Consider the presence of two ArrayLists :
ArrayList<Object> list1 = new ArrayList<Object>(); ArrayList<Object> list2 = new ArrayList<Object>();
Both lists have something in common : they are completely empty (or filled with null elements). But if I do this:
list1.add(null);
Although both of them remain completely empty , they have completely different types of behavior. And to make some methods, the results are very different :
System.out.println(list1.contains(null)); //prints true! System.out.println(list2.contains(null)); //prints false System.out.println(CollectionUtils.isNotEmpty(list1)); //prints true System.out.println(CollectionUtils.isNotEmpty(list2)); //prints false System.out.println(list1.size()); //prints 1 System.out.println(list2.size()); //prints 0
By doing some research and looking at the implementation of each of these methods, you can determine the cause of these differences, but you still donβt understand why it would be useful or useful to distinguish between these lists.
- Why add (element) doesn't check if item! = Null ?
- Why does it contain (null) say false if the list is filled with nulls ?
Thanks in advance!
EDIT:
I basically agree with the answers, but I'm still not convinced. This is the implementation of the remove method:
public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null;
So now, if I do:
ArrayList<Object> list = new ArrayList<Object>(); list.add(null); System.out.println(list.contains(null)); //prints true! list.remove(null); System.out.println(list.contains(null)); //prints false!
What am I missing?
source share