Search code examples
javaarraysarraylistduplicates

Detect duplicates in ArrayList


How could I go about detecting (returning true/false) whether an ArrayList contains more than one of the same element in Java?

I am not looking to compare "Blocks" with each other but their integer values. Each "block" has an int and this is what makes them different. I find the int of a particular Block by calling a method named "getNum" (e.g. table1[0][2].getNum()).


Solution

  • Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.

    List<Integer> list = ...;
    Set<Integer> set = new HashSet<Integer>(list);
    
    if(set.size() < list.size()){
        /* There are duplicates */
    }
    

    Update: If I'm understanding your question correctly, you have a 2d array of Block, as in

    Block table[][];

    and you want to detect if any row of them has duplicates?

    In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:

    for (Block[] row : table) {
       Set set = new HashSet<Block>(); 
       for (Block cell : row) {
          set.add(cell);
       }
       if (set.size() < 6) { //has duplicate
       }
    }
    

    I'm not 100% sure of that for syntax, so it might be safer to write it as

    for (int i = 0; i < 6; i++) {
       Set set = new HashSet<Block>(); 
       for (int j = 0; j < 6; j++)
        set.add(table[i][j]);
     ...
    

    Set.add returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns false if all you want to know is whether there are any duplicates.