Reputation: 5
I'm creating an ArrayList
of type B
:
ArrayList<B> cert= new ArrayList<B>;
B a = util.getCerts(path).iterator().next();
this.cert.add(a);
this.certNode(certs);
I'm getting a null pointer exception when I try to set the value:
void certNode(ArrayList<B> certResp)
{
ArrayList<RespNode> exp = new ArrayList<RespNode>();
for (int i = 0; i< certResp.size(); i++) {
exp.get(i).setxxx(certResp.get(i).getxxx());
exp.get(i).setxxx(certResp.get(i).getxxx().toString());
}
}
Any help would be great!
Upvotes: 0
Views: 561
Reputation: 8975
As you are creating new empty ArrayList i.e []
exp.get(i)
gives you null
Instead you can use add method of ArrayList
void certNode(ArrayList<B> certResp) {
//Here new empty list is created i.e exp=[] //no elements inside
//Suppose your certResp=[B@12312,B@123834] i.e two B class objects
ArrayList<RespNode> exp = new ArrayList<RespNode>();
for (int i = 0; i< certResp.size(); i++) { //Size of certResp=2 as it contains 2 B objects
RespNode res=new RespNode(); //Create a RespNode class as you want to add of certResp ArrayList<RespNode>
res.setxxx(certResp.get(i)); //Take value of xxx method of certResp.get(i) i.e B object xxx method and set into res.setXXX or RespNode class
exp.add(res); //add res object into ArrayList
}
}
Upvotes: 0
Reputation: 393781
Since you just created the ArrayList instance exp
, exp.get(i)
doesn't exist, so you can't call exp.get(i).setxxx(...)
.
EDIT :
Try :
void certNode(ArrayList<B> certResp) {
ArrayList<RespNode> exp = new ArrayList<RespNode>();
for (int i = 0; i< certResp.size(); i++) {
exp.add(certResp.get(i).getxxx());
}
}
It's hard to be sure without knowing the return value of certResp.get(i).getxxx()
, but if it returns RespNode
, the code above would add that RespNode
instance of the list.
Upvotes: 2
Reputation: 476
void certNode(ArrayList<B> certResp) {
ArrayList<RespNode> exp = new ArrayList<RespNode>();
for (int i = 0; i< certResp.size(); i++) {
exp.add(new RespNode()); // <-----
exp.get(i).setxxx(certResp.get(i).getxxx());
exp.get(i).setxxx(certResp.get(i).getxxx().toString());
}
}
btw you can improve syntax
void certNode(ArrayList<B> certResp) {
ArrayList<RespNode> exp = new ArrayList<RespNode>();
for (B b : certResp){
RespNode resp = new RespNode();
resp.setxxxx(b.getxxxx());
exp.add(resp);
}
}
Upvotes: 0
Reputation: 509
Your list 'exp' is empty. In the for-loop you get a value of null; calling a method from null will cause the NullPointerException.
You have to put values in the list before you try to access them.
Upvotes: 0
Reputation: 2773
The problem is here : exp.get(i)
. exp
is the newly created ArayList, so it's empty, so there is a null
at index i
Upvotes: 1