Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trouble with an arrayList

 
Shelby Simpson
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64970
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shelby Simpson wrote:My thinking is that the arrayList is populated with 10 null "spots" ...

What makes you think this?
 
Shelby Simpson
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see what your saying. My thinking was that I could test the ArrayList to see if it had been used yet. I realize that I was approaching this all wrong and should just use the size() method.

I was thinking 10 spots because its initial default capacity is 10(0-9).

thanks
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Shelby Simpson
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes I do. Java is giving me the space/memory for the arrayList but until I populate it its size is 0.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic