在自定义ArrayList中仅添加一次项目 [英] Add item only once in custom ArrayList
问题描述
我已经这样创建了自己的自定义ArrayList:
I've made my own custom ArrayList like this:
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添加数据时,它会多次添加项.我尝试过此代码仅一次添加项目:
When I'm adding data from my JSON api it adds item multiple times. I've tried this code to add the items only once it:
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>
This code is working when I use a ArrayList or ArrayList<Integer>
but not when I'm using ArrayList<Points>
有人可以向我解释如何避免重复我的清单吗?
Can anyone explain me how I can avoid duplication in my list?
推荐答案
正如您在注释中提到的Order无关紧要,我将使用 HashSet< String>
进行存储和检查 hood_name
,如果您想通过输入 hood_name
来获取 object
,则可以使用 HashMap< String,Point
代替,它返回对象在 O(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.
因此,您需要创建一个 HashSet< String>
,它将跟踪 ArrayList< Points>
中存在的所有对象的 hood_name
.
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.
}
此外,如果只想使用 ArrayList< Point>
来执行此任务,则可以覆盖 equals(Object E)
和 hashCode()
类中的方法.有关更多信息,请参考此.
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.
这篇关于在自定义ArrayList中仅添加一次项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!