Lets say I have a class foo defined like this: class foo { String a; String b; public foo(String a, String b) { this.a = a; this.b = b; } } Now I would like to make an array of class foo like this: foo myFoo[][]; How do I initialize this array and store foo objects in this it? I've tried everything I can think of but I keep getting a NullPointerException. Thanks, Frank
Tony Alicea
Desperado
Sheriff
Joined: Jan 30, 2000
Posts: 3219
posted
0
<PRE> public class Test { String a; String b; public void foo(String a, String b) { this.a = a; this.b = b; } public static void main (String[] args) { Test t[] = new Test[5]; for (int i=0; i<t.length; i++) { t[i] = new Test(); t[i].foo("A", "B"); } } } </PRE>
Tony Alicea Senior Java Web Application Developer, SCPJ2, SCWCD
Frank Carver
Sheriff
Joined: Jan 07, 1999
Posts: 6913
posted
0
Surely Tony's code only builds and initializes a one-dimensional array, where the question calls for a two-dimensional array. It looks as if the step you are missing is to call new for each "row" of the array. Here's my suggestion:
Hi, I'm just starting out with java and played around with this problem. I have the following code which gives me an ArrayIndexOutOfBounds exception when I run it. Can anyone explain why? class foo { String a; String b; public static void main (String args[]) { foo myFoo[][] = new foo [1][1]; myFoo[1][1] = new foo ("a", "b"); } public foo(String a, String b) { this.a = a; this.b = b; } }
Frank Carver
Sheriff
Joined: Jan 07, 1999
Posts: 6913
posted
0
Your problem is that arrays start from 0 not 1, so any array with a size of 1 (created by new Something[1]) only has "slot" 0. To get a second "slot", numbered 1, you need to use new Something[2].
Randi Meilach
Greenhorn
Joined: May 26, 2000
Posts: 11
posted
0
Frank, Thanks, I realized that pretty much immediately after I posted. I am coming from a language where array indexing begins at 1 and I 'keep forgetting' this little fact.
I think someone could best help you figure this one out if you were to post an example of the code that you are trying to use? Don't forget to surround your code with the [ code ] and [ /code ] ubb tags. Good Luck.