刚开始创建要存储的数据结构的时候创建在循环之外后面输出发现所有的都显示最后一个
{
List<StoreTextInformation> textAndPoints =new ArrayList<>();
StoreTextInformation storeTextInformation = new StoreTextInformation();
JSONObject jsonObject ;
jsonObject = ocrMain.getText(filePath);
JSONArray jsonArray ;
jsonArray = jsonObject.getJSONArray("AllText");
for (int i = 0; i < jsonArray.size(); i++) {
jsonObject = (JSONObject) jsonArray.get(i);
// System.out.println(jsonObject);
String text = jsonObject.getString("text");
// System.out.println("shuchu"+Text);
storeTextInformation.setText(text);
JSONArray boxPoint = jsonObject.getJSONArray("boxPoint");
jsonObject = (JSONObject) boxPoint.get(0);
int x = Integer.parseInt(jsonObject.getString("x"));
int y = Integer.parseInt(jsonObject.getString("y"));
Point upLeftLocationPoint = new Point(x, y);
storeTextInformation.setUpLeftLocationPoint(upLeftLocationPoint);
jsonObject = (JSONObject) boxPoint.get(0);
int x1 = Integer.parseInt(jsonObject.getString("x"));
int y1 = Integer.parseInt(jsonObject.getString("y"));
Point lowRightLocationPoint = new Point(x1, y1);
storeTextInformation.setLowRightLocationPoint(lowRightLocationPoint);
textAndPoints.add(storeTextInformation);
}
return textAndPoints;
}
之所以将 Objec new在循环的外面,就是想节省空间,(不用在循环中每次循环斗殴需要new一个对象)。但是忘了考虑到:
ArrayList集合里存的是一个对象的引用。当我们改变obj时,因为ArrayList.add的是 obj的引用,之前的元素都指向了同一个对象 obj,所以在改变obj时,之前添加的也会随之改变。,
解决方法:
将 Objec new在循环的里面。
public List<StoreTextInformation> getChineseTextLocation(String filePath) {
List<StoreTextInformation> textAndPoints =new ArrayList<>();
JSONObject jsonObject ;
jsonObject = ocrMain.getText(filePath);
JSONArray jsonArray ;
jsonArray = jsonObject.getJSONArray("AllText");
for (int i = 0; i < jsonArray.size(); i++) {
StoreTextInformation storeTextInformation = new StoreTextInformation();
jsonObject = (JSONObject) jsonArray.get(i);
// System.out.println(jsonObject);
String text = jsonObject.getString("text");
// System.out.println("shuchu"+Text);
storeTextInformation.setText(text);
JSONArray boxPoint = jsonObject.getJSONArray("boxPoint");
jsonObject = (JSONObject) boxPoint.get(0);
int x = Integer.parseInt(jsonObject.getString("x"));
int y = Integer.parseInt(jsonObject.getString("y"));
Point upLeftLocationPoint = new Point(x, y);
storeTextInformation.setUpLeftLocationPoint(upLeftLocationPoint);
jsonObject = (JSONObject) boxPoint.get(0);
int x1 = Integer.parseInt(jsonObject.getString("x"));
int y1 = Integer.parseInt(jsonObject.getString("y"));
Point lowRightLocationPoint = new Point(x1, y1);
storeTextInformation.setLowRightLocationPoint(lowRightLocationPoint);
textAndPoints.add(storeTextInformation);
}
return textAndPoints;
}
添加静态修饰也会存在这个问题
static(Student 类中)就是这个修饰符,
让修饰的属性变为静态,
意味着该类的所有对象共享同一个属性
所以尽管集合里存的是不同的对象,但是对象的属性还是同一个值
还有就是对list的使用必须初始化
List<StoreTextInformation> textAndPoints; 直接会提醒没有初始化
List<StoreTextInformation> textAndPoints =new ArrayList<>();