Définition des collections dans des écrans personnalisés
Question
J'écris une classe d'écriture personnalisée avec des collections Java.Quelqu'un peut-il me dire comment ma mise en œuvre est mal Je passe deux collections Java dans le constructeur
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);
}
}
}
C'est l'erreur que je reçois 'java.lang.nullpointereException'
La solution
Vous devez initialiser la collection avant de l'utiliser comme I.E.
following=new ArrayList<IntWritable>();
Vous venez de déclarer après et des tweets mais ne l'initialisaient pas.
Autres conseils
initialiser un membre avant de l'utiliser.Dans votre cas, faites-la
ArrayList<IntWritable> following = new ArrayList<IntWritable>();
ArrayList<Text> tweets= new ArrayList<Text>;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow