Add item only once in custom ArrayList

后端 未结 3 559
春和景丽
春和景丽 2021-01-23 08:28

I\'ve made my own custom ArrayList like this:

public class Points {
    String hoodName;
    Double points;
    Integer hoodId;
    public Points(String hN, Doub         


        
3条回答
  •  抹茶落季
    2021-01-23 09:30

    If the sequence is not important, then you can use a HashMap to uniquely identify them.

    HashMap pointMap = new HashMap<>();
    String hoodName = jsonObject.getString("hood_name");
    Point point = new Point(jsonObject.getString("hood_name"),
                      jsonObject.getDouble("points"),
                      jsonObject.getInt("hood_id"))
    if (!points.containsKey(hoodName)) pointMap.put(hoodName, point);
    

    In fact, if you will always want to overwrite the old point with new point which has the same hoodName, you do not need to check whether the Point exists in your list. Calling pointMap.put(key, object) will always replace the object with the same key.

提交回复
热议问题