This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I need to be able to check an arrayList to see if index 0 is null. I use a get(0) and put it into an element type variable. The problems that it keeps throwing an error saying index 0 size 0. My thinking is that the arrayList is populated with 10 null "spots" and that I should be able to check those spots to see if they are null. Help please.
If you haven't added anything to a List, you can't get anything out of it, not even null. So before you add anything, even get(0) will throw an exception. After you call add() twice, you can call get(0) and get(1). If you call add() 3 times, you can call get(0), get(1), get(2), and so on.
Note that an element having a value of null is completely different from an element not even being present in the first place.
Shelby Simpson wrote:
I was thinking 10 spots because its initial default capacity is 10(0-9).
So now you understand the difference between the capacity and the number of elements actually in the list?
Note that the backing array does have 10 elements, and they are all null (unless the implementor chose to set them to some other dummy value, which is possible, but would be silly), but that's an implementation detail, and has nothing to do with what's actually held by the List.
Joined: Feb 17, 2013
Yes I do. Java is giving me the space/memory for the arrayList but until I populate it its size is 0.