如何不将重复项添加到数组列表中

问题描述 投票:0回答:5

编辑我没有正确解释自己,因此我将再次正确询问。

我有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文件,我希望仅将第一个和第三个对象添加到数组中。

java android
5个回答
1
投票

如果您不希望集合中有重复项,则应考虑为什么要使用允许重复项的集合。删除重复元素的最简单方法是将内容添加到Set中(不允许重复),然后将Set添加回ArrayList:

Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);

当然,这会破坏ArrayList中元素的顺序。


0
投票

同意以上所有答案。您需要使用Set而不是List。

与Set一起,您可能需要在给定参数的车库对象中覆盖等于和哈希码

例如:-如果您的要求是车库名称不应重复,则使用车库名称参数覆盖等号和哈希码


0
投票

将数组列表传递给(设置为该集合不包含重复项)

set<type>  garageSet = new Hashset<type>(garage.getGarage());

0
投票

是的,如果您需要一个集合而不存储重复的项目,我建议最好使用HashSet,但如果需要保留订单,请使用LinkedHashSet

但是如果要使用数组列表,则可以将旧列表包装到集合中以删除重复项,然后将该集合再次包装在列表中。例如:

List<String> newList = new ArrayList<String>(new HashSet<String>(arraylist));

0
投票

我用另一种方式修复了它。在车库对象类中,我重写了equals方法:

@Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            GarageObject that = (GarageObject) o;
            return garageNumber == that.garageNumber;
        }

比片段类多添加if条件:

for (int i = 0; i < 13273; i++) {
                if (garage.getGarage().get(i).garageCity.equals(AddressSingleton.getInstance().getCurrentAddress())) {
                    if (!garageObjects.contains(garage.getGarage().get(i))) {
                        garageObjects.add(garage.getGarage().get(i));
                    }
                }
            }

不是很好。

© www.soinside.com 2019 - 2024. All rights reserved.