Results 1 to 7 of 7
Thread: nullPointerExceptioin
- 03-07-2011, 10:47 PM #1
Member
- Join Date
- Oct 2010
- Posts
- 23
- Rep Power
- 0
nullPointerExceptioin
I was just wondering about this what it means and how to avoid it.
this might be an obvious question but do i have to declare the size of the array before i use it ?Java Code:public class Gallery { String galleryName; int gallerySize; int i = 0; GalleryArt galleryContents [] ; Gallery(){ } public void insertGalleryContents(GalleryArt x ) { galleryContents [i] = x; i++; }
i have the size i want to use declared when my gallery object is created but i cant just pop that variable in?
would using an array list sort this ?
- 03-07-2011, 10:52 PM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
The problem is you only declared a reference to the array, you forgot to create the object that the array reference is pointing to. Therefor, your reference is pointing to a null object, nullpointer exception is thrown.
- 03-07-2011, 11:04 PM #3
Member
- Join Date
- Oct 2010
- Posts
- 23
- Rep Power
- 0
ok thanks sunde. i actually didn't forget i just thought java could do some magic for me :) also i was wondering if you were making a class with arrays and you didn't want to define a size for the array an array list would be the way to go.?
i couldn't use a class variable set up int the constructor e.g array ra [] = new array[class variable]
don't think this make much sense haha but il ask now because it seems like something i might come across fairly often
- 03-07-2011, 11:08 PM #4
It is impossible to create an array of undetermined size. If you want to do that then yes you need to use a List or some other Collection.
Alternatively you can ask the user the array size and pass that value to the constructor of your class.
Java Code:class Foo { int[] array; Foo(int size) { array = new array[size]; } }
- 03-07-2011, 11:14 PM #5
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
The real nice part of using an arraylist is that it can easily change sizes. The array can't easily be increased in size, it's possible but not as simple as just using a list.
- 03-07-2011, 11:33 PM #6
Member
- Join Date
- Oct 2010
- Posts
- 23
- Rep Power
- 0
cheers guys exactly what i wanted to know appreciate it :)
- 03-07-2011, 11:36 PM #7
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks