關於java list新增元素後前面的會被後面的覆蓋的問題
阿新 • • 發佈:2020-12-18
剛開始建立要儲存的資料結構的時候建立在迴圈之外後面輸出發現所有的都顯示最後一個
{ 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<>();