当我尝试存储字节数组时,为什么会出现java.lang.NullPointerException?你能解释一下为什么它不能以这种方式工作吗?如果没有NullPointerException,我怎样才能做得更好?
Exception in thread "Thread-3" java.lang.NullPointerException
at test.Screenblocks_Data.set_Image(Screenblocks_Data.java:13)
at desktop_share_client.ScreenBlocks.run(ScreenBlocks.java:120)
public class Screenblocks_Data implements java.io.Serializable {
public int Screenblocks_Counter = 0;
public int[][] positions = new int[200][2];
public Jpeg[] sub_images = new Jpeg[200];
public Screenblocks_Data() {
}
public void set_Image(byte[] temp_image) {
sub_images[Screenblocks_Counter].set_sub_image(temp_image);
}
public byte[] get_Image(int position) {
return sub_images[Screenblocks_Counter].sub_image;
}
}
public class Jpeg {
public byte[] sub_image = null;
public void set_sub_image(byte[] temp_image) {
sub_image = new byte[temp_image.length];
sub_image = temp_image;
}
}
答案 0 :(得分:8)
你刚买了一个袋装200个苹果。但是如果没有装满袋子,你就是想吃一个苹果:)。
您从未初始化第0个(或Screenblocks_Counter
元素)元素。首先,您必须在零位置添加元素,然后访问它。
sub_images[Screenblocks_Counter] = new Jpeg();
sub_images[Screenblocks_Counter].set_sub_image(temp_image);