0

I want to make an array of size 150 of the class Info

public class Info {
    int Group;
    String Name;
}

But I have the exception occur after

 public class Mover {
        static Info[] info=new Info[150];
            public static void main(String[] args) {
            info[0].Group=2;//I get error here
        }
}

I'm not sure if there is a better way to do what a want to do, but I don't want to use a multidimensional array. I'm simply trying to add information to the group, so I'm confused.

5
  • First you've to create Info object, then only you can set value to its attribute. Commented Apr 8, 2015 at 5:43
  • You have to initialize an object before you can use the methods Commented Apr 8, 2015 at 5:45
  • Assign objects in your array ... currently info[0] ... info[n] are null and any operation on these array elements will lead to NPE Commented Apr 8, 2015 at 5:45
  • 1
    This really should be marked as a duplicate of something, but I can't find any of the other 15,326 questions that have asked this. Commented Apr 8, 2015 at 5:46
  • 1
    Sorry for the trouble, I just thought that it would automatically instantiate each of the locations Commented Apr 8, 2015 at 5:48

2 Answers 2

1

doing new Info[150] simply instantiates an array of size 150. All elements within the array have not been instantiated and are therefore null.

So when you do info[0] it returns null and you're accessing null.Group.

You have to do info[0] = new Info() first.

Sign up to request clarification or add additional context in comments.

2 Comments

Do you know how I can do that in a simple command rather than typing it all out? Btw, thanks alot.
Yeah, you can do Arrays.fill(info, new Info()) and it will instantiate all elements in the array.
0

This static Info[] info=new Info[150]; is creating an array of 150 objects of type info pointing to NULL. You have to do this to get this working

for(int i = 0; i< 150; i++) info[i] = new Info();

Then you can use these objects

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.