aspose file tools*
The moose likes Beginning Java and the fly likes Trouble with an arrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trouble with an arrayList" Watch "Trouble with an arrayList" New topic
Author

Trouble with an arrayList

Shelby Simpson
Greenhorn

Joined: Feb 17, 2013
Posts: 26
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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: Jan 10, 2002
Posts: 61066
    
  66

Shelby Simpson wrote:My thinking is that the arrayList is populated with 10 null "spots" ...

What makes you think this?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Shelby Simpson
Greenhorn

Joined: Feb 17, 2013
Posts: 26
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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: Feb 17, 2013
Posts: 26
Yes I do. Java is giving me the space/memory for the arrayList but until I populate it its size is 0.
 
 
subject: Trouble with an arrayList