Results 1 to 7 of 7
Thread: Problem with an array of objects
- 02-27-2012, 04:27 AM #1
Member
- Join Date
- Feb 2012
- Posts
- 2
- Rep Power
- 0
Problem with an array of objects
First, the code to its bare-bones:
What I want to do is to create an array where each element of the array is a Foo object. By calling bar[0], I get the reference to the first Foo object, .... The code above compiles without a problem, but I get a null pointer exception on the line indicated above.Java Code:public class FooMain { public static void main(String[] args) { Foo[] bar = new Foo[3]; System.out.println(bar[0].x); //Error thrown here } } public class Foo { public int x; public Foo() { x = 12; } }
I really don't know what the problem is. If I create a single Foo (not in an array), it works correctly. If I create an array of int, it works too. But an array of Foo just won't work.
Thanks in advance for your help.
-
Re: Problem with an array of objects
Object arrays are collections of variables, not objects, and they have to be filled with objects to work. One way to think of arrays is as if you were creating a parking lot. Starting out it has no cars, and you have to fill it with cars for each space to have any "meaning".
- 02-27-2012, 04:35 AM #3
Senior Member
- Join Date
- Feb 2011
- Location
- Georgia, USA
- Posts
- 122
- Rep Power
- 0
-
Re: Problem with an array of objects
- 02-27-2012, 04:41 AM #5
Member
- Join Date
- Feb 2012
- Posts
- 2
- Rep Power
- 0
Re: Problem with an array of objects
I thought the objects where getting initialized by calling the array. Is there a pretty way to do so, or only like this:
EDIT: I guess Fubarable pretty much answered a second before I posted.Java Code:for(int i=0;i<bar.length;i++) { bar[i] = new Foo(); }
-
Re: Problem with an array of objects
Only the array is initialized by your first code, not the items in the array. You can initialize it in other ways if desired:
Java Code:Foo[] bar = {new Foo(), new Foo(), new Foo(), new Foo(), new Foo(), new Foo(), new Foo(), new Foo()};
- 02-27-2012, 04:49 AM #7
Senior Member
- Join Date
- Feb 2011
- Location
- Georgia, USA
- Posts
- 122
- Rep Power
- 0
Similar Threads
-
Array of objects
By EnSlavingBlair in forum New To JavaReplies: 4Last Post: 09-30-2011, 01:27 PM -
How to convert array of Objects into array of Strings
By elenora in forum Advanced JavaReplies: 1Last Post: 06-10-2011, 03:48 PM -
help with and array of objects
By hoosierfan24 in forum New To JavaReplies: 5Last Post: 01-23-2011, 02:45 AM -
Array of objects
By Saletra in forum New To JavaReplies: 2Last Post: 07-31-2010, 12:16 PM -
Array of Objects
By bluefloyd8 in forum New To JavaReplies: 5Last Post: 01-22-2008, 06:27 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks