简体   繁体   中英

How to Compare element of Arraylist<Integer>

I wrote below code to get duplicate elements from Arraylist. My aerospikePIDs list doesn't have any duplicate value but still when I am executing below code it is reading if condition.

ArrayList<Integer> aerospikePIDs = new ArrayList<Integer>();    

ArrayList<Integer> duplicates = new ArrayList<Integer>();
    boolean flag;
    for(int j=0;j<aerospikePIDs.size();j++) {
        for(int k=1;k<aerospikePIDs.size();k++) {
            if(aerospikePIDs.get(j)==aerospikePIDs.get(k)) {
            duplicates.add(aerospikePIDs.get(k));
            flag=true;
            }
            if(flag=true)
System.out.println("duplicate elements for term " +searchTerm+duplicates);
    }   
                }

Your inner loop should start from j + 1 (not from 1 ), otherwise when j = 1 (second iteration of j), for k = 1 (first iteration of k for j value equals to 1).

aerospikePIDs.get(j)==aerospikePIDs.get(k) 

returns true .

So the code should be:

ArrayList<Integer> aerospikePIDs = new ArrayList<Integer>();    

ArrayList<Integer> duplicates = new ArrayList<Integer>();

for (int j = 0; j < aerospikePIDs.size(); j++) {
    for (int k = j + 1; k < aerospikePIDs.size(); k++) {
        if (aerospikePIDs.get(j)==aerospikePIDs.get(k)) {
            duplicates.add(aerospikePIDs.get(k));
            System.out.println("duplicate elements for term " +searchTerm+duplicates);
        }
    }   
}

Note: the flag is not necessary, because if you addeda duplicate you can print it directly in the if, without defining new unnecessary variables and code.

Use higher level abstractions:

  1. Push all list elements into a Map<Integer, Integer> - key is the entry in your PIDs list, value is a counter. The corresponding loop simply checks "key present? yes - increase counter; else, add key with counter 1".
  2. In the end, you can iterate that map, and each entry that has a counter > 1 ... has duplicates in your list; and you even get the number of duplicates for free .

And questions/answers that show you nice ways to do such things ... are posted here on almost daily basis. You can start here for example; and you only need to adapt from "String" key to "Integer" key.

Really: when working with collections, your first step is always: find the most highlevel way of getting things done - instead of sitting down and writing such error-prone low-level code as you just did.

You are iterating using the same arraylist. You are checking every data in inner for loop, for sure it will display duplicates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM