Add Item Only Once In Custom Arraylist
Solution 1:
As you mentioned in the comments that Order doesn't matter , I would have an HashSet<String>
to store and check the hood_name
and If you want to get object
by entering hood_name
you can use HashMap<String,Point
instead which returns the object in O(1)
time.
So You need to create a HashSet<String>
which will keep track of hood_name
of all objects present in the ArrayList<Points>
.
HashSet<String> all_ids=new HashSet<String>();
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<Point>
to execute this task , You can override equals(Object E)
and hashCode()
methods in Point
class. For more information , refer this.
Solution 2:
If the sequence is not important, then you can use a HashMap
to uniquely identify them.
HashMap<String, Point> pointMap = newHashMap<>();
StringhoodName= jsonObject.getString("hood_name");
Pointpoint=newPoint(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.
Solution 3:
In this case the Points object use default equals()
method which is inconsistent. As you want to use contains
method, you should implement equals()
method like this way.
publicclassPoints {
String hoodName;
Double points;
Integer hoodId;
publicPoints(String hN, Double p, Integer hI) {
hoodName = hN;
points = p;
hoodId = hI;
}
publicDoublegetPoints() {
return points;
}
publicIntegergetHoodId() {
return hoodId;
}
publicStringgetHoodName() {
return hoodName;
}
@Overridepublicbooleanequals(Object obj) {
if (!(obj instanceofPoints)) {
returnfalse;
}
Points points = (Points) obj;
return points.getHoodName().equals(getHoodName().trim()) &&
points.getHoodId() == getHoodId()
&& points.getPoints() == getPoints();
}
}
If you ovverride
equals()
method, you can easily use it in ArrayList<Points>
. Hope it will work in your case.
Post a Comment for "Add Item Only Once In Custom Arraylist"