0

I have two classes:

FirstClass{
    private int id;
    private SecondClass[] arrayofSecond;
    private int ind;
    public FirstClass(){}
    public FirstClass(int id){
         this.id=id;
    }
    public void addElements(SecondClass e){
         arrayofSecond[ind]=e;
         ind++;
    } 
    public SecondClass[] getArraySecondClass(){
        return arrayofSecond;
    }    
}

SecondClass{
    private int id;
    private SecondClass(){}
    private SecondClass(int id){
          this.id=id;
    }
    public int getId(){
          return id;
    }
}

Now I need to get the array that has been filled in the FirtsClass in the Main program, like this:

FirstClass f1=new FirstClass(10);
SecondClass s1=new SecondClass(10);
SecondClass s2=new SeconClass(20);
f1.addElements(s1);
f1.addElements(s2);
FirstClass f=null;
SecondClass s[];
s=f.getArraySecondClass();
for (int i=0;i<s.length;i++){
    System.out.println(s[i].getId());
}

The problem is that I get an error of Null pointer exception. I have read that maybe this is not a correct way to do this by the principle of "not talk to strangers", but I do not see another way to make this.

Any help?

5 Answers 5

2

Why are you creating a f variable when you already have f1?

FirstClass f1=new FirstClass(10);
SecondClass s1=new SecondClass(10);
SecondClass s2=new SeconClass(20);
f1.addElements(s1);
f1.addElements(s2);

SecondClass s[];
s=f1.getArraySecondClass();
for (int i=0;i<s.length;i++){
    System.out.println(s[i].getId());
}
Sign up to request clarification or add additional context in comments.

Comments

0

You'll have to initialize the arrayofSecond.

In the constructor of FirstClass you'll have to do arrayofSecond = new SecondClass[10]; or any other length you desire.

Comments

0
FirstClass f=null;

should be

FirstClass f= new FirstClass(10);

f is set to null so you are getting NPE.

Comments

0

You have to initiate the arrayOfSecond variable to avoid NullPointerException.

change private SecondClass[] arrayofSecond; to e.g.

    private SecondClass[] arrayofSecond = new SecondClass[10];

Comments

0

First, you should never allow outer classes to access your private data fields directly. So instead of

public SecondClass[] getArraySecondClass(){
    return arrayofSecond;
}

you should do something like

public SecondClass[] getArraySecondClass(){
    return (SecondClass[])arrayofSecond.clone();
} 

Besides that, you need to initialize arrayOfSecond in FirstClass constructor and

f.getArraySecondClass();

isnt't the best idea when f is null.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.