Java - Custom type nested in class

Pinco :

I am once again asking for technical support.

I need to define a custom type inside a class, I've done it like this:

public class MainClass {
    private class CustomType {
        public byte[] varA;
        public int varB;

        public CustomType() {
            varA = new byte[3];   
            varB = 13;
        }
    }

    private CustomType[] myArray;


    public MainClass() {
        myArray = new CustomType[1024]
        System.out.println(this.CustomType[0].varB);
    }
}

When I run it throws a NullPointerException at System.out.println(this.CustomType[0].varB);

I've tested if myArray gets properly initialized with 1024 elements and it does, however I can't seem to access them.

I just moved from C++ to Java so I'm still getting used to it, am I missing something blatant?.

Joop Eggen :

Two things,

  • You must instantiate CustomType.
  • CustomType does not need access to MainClass.this so you can make it static.

So

public class MainClass {
    private static class CustomType {
        public byte[] varA;
        public int varB;

        public CustomType() {
            varA = new byte[3];   
            varB = 13;
        }
    }

    private CustomType[] myArray;


    public MainClass() {
        myArray = new CustomType[1024];
        for (int i = 0; i < myArray.length; ++i) {
            this.CustomType[i] = new CustomType();
        }
        // Or
        Arrays.setAll(myArray, CustomType::new);
        System.out.println(this.CustomType[0].varB);
    }
}

Not making it static stores a MainClass.this in every CustomType instance which is unnecessary overhead.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=292368&siteId=1