自定义可写文件中的java定义集合

quhf5bfb  于 2021-06-03  发布在  Hadoop
关注(0)|答案(2)|浏览(376)

我正在编写一个自定义的可写类,其中包含一些java集合。有人能告诉我我的实现是怎么错的吗?我在构造函数中传递了两个java集合

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);
    }
}

}

这就是我得到“java.lang.nullpointerexception”的错误

vulvrdjw

vulvrdjw1#

在使用前初始化成员。在你的情况下,这样做

ArrayList<IntWritable> following = new ArrayList<IntWritable>();
ArrayList<Text> tweets= new ArrayList<Text>;
ifsvaxew

ifsvaxew2#

您必须在使用集合之前初始化它,例如。

following=new ArrayList<IntWritable>();

你只需要声明following和tweets,而不是初始化它。

相关问题