在自定义 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
时有效,但在我使用 ArrayList
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
来存储和检查hood_name
并且如果你想通过输入 hood_name
来获取 object
你可以使用 HashMap
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
,它将跟踪ArrayList
中存在的所有对象的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
来执行这个任务,你可以重写equals(Object E)
和hashCode()
方法.有关详细信息,请参阅此.Point
类中的
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屋!