Reputation: 3477
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?
Upvotes: 0
Views: 109
Reputation: 9590
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());
}
Upvotes: 2
Reputation: 4319
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.
Upvotes: 0
Reputation: 203
You have to initiate the arrayOfSecond variable to avoid NullPointerException.
change private SecondClass[] arrayofSecond;
to e.g.
private SecondClass[] arrayofSecond = new SecondClass[10];
Upvotes: 0
Reputation: 12843
FirstClass f=null;
should be
FirstClass f= new FirstClass(10);
f
is set to null
so you are getting NPE
.
Upvotes: 0
Reputation: 48065
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.
Upvotes: 0