我是Android / Java中的一个非常新的程序员。以下是产生不清楚的结果的代码。另外,我提出了找到的“解决方案”,但并不满足我的好奇心。 `
//Here I define my class to hold data
public class ImageData {
Date date;
byte[] image;
}
// Here I initialize the array photos and put getter and setter
abstract class Variables {
public static ImageData photos = new ImageData[4];
static ImageData getPhotos(int n) {
return photos[n];
}
static void setPhotos(ImageData photos, int n) {
Variables.photos[n] = photos;
}
}
// Here, at the very begining of app, initialize the array
Variables.photos[0] = new ImageData();
Variables.photos[1] = new ImageData();
Variables.photos[2] = new ImageData();
Variables.photos[3] = new ImageData();
// And now, I use those objects
public void run() {// This DOES NOT WORK (all photos have the last image)
// get 4 photos and save result in global
int count;
ImageData localPhoto = new ImageData();
// clear global (at least the byte[]
for (count = 0; count > 4; count++) {
localPhoto.image = null;
setPhotos(localPhoto, count);
}
// take 4 pictures
for (count = 0; count < 4; count++) {
localPhoto.image = getPhoto(ipCamera, port);
localPhoto.date = Calendar.getInstance().getTime();
setPhotos(localPhoto, count);
}
//...............................
}
在我发表评论时,所有四张photos.image都是相同的(还有日期)。 我使用以下方法工作:
public void run() { // This WORKS
// get 4 photos and save result in global
int count;
ImageData localPhoto; // declared, not initialized
// clear global (at least the byte[] )
for (count = 0; count > 4; count++) {
localPhoto = new ImageData(); // <<<<<<<<<<<<<<<<< NEW
localPhoto.image= null;
setPhotos(localPhoto, count);
}
// take 4 pictures
for (count = 0; count < 4; count++) {
localPhoto = new ImageData(); // <<<<<<<<<<<<<<<<< NEW
localPhoto.image = getPhoto(ipCamera, port);
localPhoto.date = Calendar.getInstance().getTime();
setPhoto(localPhoto, count);
}
//...............................
}
但是我真的不明白为什么会这样。而且,我想以一种更优雅的方式初始化数组,但找不到。 谢谢您的评论。谢谢!
答案 0 :(得分:0)
public void run() {// This DOES NOT WORK (all photos have the last image)
// get 4 photos and save result in global
int count;
ImageData localPhoto = new ImageData();
上面的行创建一个ImageData()
对象,并为其命名为localPhoto
。
// clear global (at least the byte[]
for (count = 0; count > 4; count++) {
localPhoto.image = null;
这将设置先前创建的对象中的image
字段。请注意,它在同一对象中将image
设置为四次。
setPhotos(localPhoto, count);
现在您调用setPhotos()
并将引用传递给相同的对象四次。
}
// take 4 pictures
for (count = 0; count < 4; count++) {
localPhoto.image = getPhoto(ipCamera, port);
localPhoto.date = Calendar.getInstance().getTime();
setPhotos(localPhoto, count);
与上面的描述一样,每次重复此循环时,您都使用对同一对象的引用。因此,数组中的所有四个元素都指向同一个对象。
}
}
现在看看您的更改
for (count = 0; count > 4; count++) {
localPhoto = new ImageData(); // <<<<<<<<<<<<<<<<< NEW
localPhoto.image= null;
setPhotos(localPhoto, count);
}
这可解决此问题,因为您在每次迭代中都创建了一个新对象。每次将引用localPhoto
分配给一个不同的对象。
要更好地理解这一点,请阅读参考变量如何在Java中工作。