my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Putting data into array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Putting data into array" Watch "Putting data into array" New topic
Author

Putting data into array

Arthur Donting
Greenhorn

Joined: Mar 22, 2009
Posts: 10
hey guys, I need to create an array of classes. for now i have this fragment:



I keep getting NullPointerException. When i use this:


everything works just fine but i need to have an array. Coud anyone help out with this?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39044
    
  23
Have you really been given a CarData class with public fields like that? Very bad design.

Have you initialised the array to anything before trying to gain access to its 1st element? If not, you will suffer a NullPointerException.
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
Thats becaus you have to initialize your array indexes with Cars.



As a little advice, try not to access properties directly. Encapsulate them by using JavaBean Properties.


JDBCSupport - An easy to use, light-weight JDBC framework -
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39044
    
  23
Have you initialised the 1st element in the array to anything? If not you will suffer a NullPointerException there too.

Remember if you declare anything, that doesn't have any value until you initialise it. If you have a 15-member array, then you have 15 references which all point to null until you tell them otherwise.
Arthur Donting
Greenhorn

Joined: Mar 22, 2009
Posts: 10
solved everything. thanks a lot guys
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39044
    
  23
You're welcome
 
GeeCON Prague 2014
 
subject: Putting data into array