只有一次添加的項目我做了我自己的自定義的ArrayList是這樣的:定製的ArrayList
public class Points {
String hoodName;
Double points;
Integer hoodId;
public Points(String hN, Double p, Integer hI){
hoodName = hN;
points =p;
hoodId = hI;
}
public Double getPoints() {
return points;
}
public Integer getHoodId() {
return hoodId;
}
public String getHoodName() {
return hoodName;
}
}
當我從它添加項目進行了多次我的JSON API添加數據。我試過這個代碼新增的項目只有一次吧:
if (!points.contains(jsonObject.getString("hood_name"))) {
points.add(new Points(jsonObject.getString("hood_name"), jsonObject.getDouble("points"), jsonObject.getInt("hood_id")));
}
如果也試過這樣:
if (!points.contains(Points(jsonObject.getString("hood_name"), jsonObject.getDouble("points"), jsonObject.getInt("hood_id")))) {
points.add(new Points(jsonObject.getString("hood_name"), jsonObject.getDouble("points"), jsonObject.getInt("hood_id")));
}
此代碼的工作,當我使用的ArrayList或ArrayList<Integer>
而不是當我使用ArrayList<Points>
誰能解釋我如何能避免我的列表中的重複?
hoodName是在列表中只有一個屬性,你可以不檢查包含與對象的一個屬性,創建'Points'對象,覆蓋等於在'Points'那麼你的代碼將被還曾 –
方法,看你的代碼,看起來像Point的順序並不重要?在這種情況下,使用Map或HashMap可能會更好。 – tingyik90
@ tingyik90沒有順序並不重要 –