Add item only once in custom ArrayList

后端 未结 3 561
春和景丽
春和景丽 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:15

    As you mentioned in the comments that Order doesn't matter , I would have an HashSet to store and check the hood_nameand If you want to get object by entering hood_name you can use HashMap instead which returns the object in O(1) time.

    So You need to create a HashSet which will keep track of hood_name of all objects present in the ArrayList.

    HashSet all_ids=new HashSet();
    
    if (!all_ids.contains(jsonObject.getString("hood_name"))) 
    {
        points.add(new Points(jsonObject.getString("hood_name"), jsonObject.getDouble("points"), jsonObject.getInt("hood_id")));
        all_ids.add(jsonObject.getString("hood_name")); //You need to add it to set as Now it exists in the list.                     
    }
    

    Further more , If you want to only use ArrayList to execute this task , You can override equals(Object E) and hashCode() methods in Point class. For more information , refer this.

提交回复
热议问题