java如何不向数组列表中添加重复项
已编辑 我没有解释清楚,所以我会再问清楚
我有json对象的数组列表。 我的json包含13000个对象,每个对象包含几个值。 在某些情况下,对象中的一个值是相同的。例如:
这就是我现在所拥有的:
public void readData() {
String json_string = null;
try {
InputStream inputStream = getActivity().getAssets().open("garages.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
json_string = new String(buffer, StandardCharsets.UTF_8);
Gson gson = new Gson();
garage = gson.fromJson(json_string, Garage.class);
//In this loop I'm checking address and if it equal to current user address , I'm add this object to Array list.
for (int i = 0; i < 13476; i++) {
if (garage.getGarage().get(i).garageCity.equals(AddressSingleton.getInstance().getCurrentAddress())) {
garageObjects.add(garage.getGarage().get(i));
Log.d("TheDataIS", "readData: " + garage.getGarage().get(i).garageName);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
如果查看JSON文件,可以看到第一个车库和第二个车库中的名称相同,但另一个值garage_code不同。 在这种情况下,我不想将这两个对象都添加到数组中
{
"garage" : [
{
"garage_code":16,
"garage_name": "New York Garage",
"phone_number": "123123",
"city":"New York"
},{
"garage_code":21,
"garage_name": "New York Garage",
"phone_number": "123123",
"city":"New York"
},{
"garage_code":51,
"garage_name": "My Garage",
"phone_number": "089898",
"city":"Some city"
},...
对于这个json文件,我希望只将第一个和第三个对象添加到数组中
# 1 楼答案
将数组列表传递给(设置)此集合不包含重复项
# 2 楼答案
我用另一种方式修复了它。 在车库对象类中,我重写了equals方法:
而在片段类I中添加了额外的if条件:
不,它很管用
# 3 楼答案
是的,如果你需要一个不存储重复项目的集合,我建议最好使用
HashSet
,但如果你需要保留顺序,请使用LinkedHashSet
但是如果希望使用数组列表,则可以将旧列表包装到一个集合中,以删除重复项,然后再次将该集合包装到一个列表中。例: