Defining collections in custom writables
Question
I am writing a custom writable class with some java collections in it. Can anyone tell me how is my implementation wrong I am passing two java collections in the constructor
public class details implements Writable {
IntWritable id;
Text username;
ArrayList<IntWritable> following;
ArrayList<Text> tweets;
public details (int id, String u, ArrayList<Integer> f, ArrayList<String> t){
this.id = new IntWritable(id);
this.username = new Text(u);
int i = 0;
while(i<f.size()){
this.following.add(new IntWritable(f.get(i)));
i++;
}
i = 0;
while(i<t.size()){
this.tweets.add(new Text(t.get(i)));
i++;
}
}
@Override
public void readFields(DataInput in) throws IOException {
// TODO Auto-generated method stub
id.readFields(in);
username.readFields(in);
int size=in.readInt();
for(int i=0;i<size;i++){
IntWritable temp = new IntWritable();
temp.readFields(in);
following.add(temp);
}
size=in.readInt();
for(int i=0;i<size;i++){
Text temp = new Text();
temp.readFields(in);
tweets.add(temp);
}
}
@Override
public void write(DataOutput out) throws IOException {
// TODO Auto-generated method stub
id.write(out);
username.write(out);
out.writeInt(following.size());
for(IntWritable s : following){
s.write(out);
}
out.writeInt(tweets.size());
for(Text s : tweets){
s.write(out);
}
}
}
this is the error i am getting 'java.lang.nullpointerException'
Solution
You have to initialize collection before using it like i.e.
following=new ArrayList<IntWritable>();
You just declare following and tweets but not initialized it.
OTHER TIPS
Initialize member before using it. in your case do this
ArrayList<IntWritable> following = new ArrayList<IntWritable>();
ArrayList<Text> tweets= new ArrayList<Text>;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow