Finding duplicates in java Array

好久不见. 提交于 2020-01-06 03:11:10

问题


Anyway, I have this extremely simple java program to find out if 2 objects in an array are the same. How ever when I run it when a set of unique objects it always returns 1 error, If I add more objects that are the same it counts as normal.

This is the code;

int[] array= new int[] {1,245,324,523};

    int size = array.length;
    int error=0;
    System.out.println(error);

    int i = 0;
    for(i=0; i<size; i++){

        if(array[0] == array[i]){
            error= error +1;
        }
        System.out.println(error);
    }

回答1:


The 1 error is because you're comparing array[0] with array[0], which is of course equal to itself.

If you want to find all pairwise duplicates, you will need to do a double loop:

for(int i=0;i<size;i++){
    for(int j=i+1;j<size;j++){
        if(array[i] == array[j]){
            if(i!=j){
                error = error + 1;
            }
        }
    }
}

You'll notice a few things from this code:

  • j starts at i+1, not at 0.
  • error is only incremented when i!=j

The first is because you're taking turns with each element in your array to compare with every other element. By the time its turn comes around (in the outer loop), it's already been compared to the elements before it, and should not be compared with them again.

The second is because you'll end up comparing an element to itself for each outer loop. You don't want to count it as an error.




回答2:


You're starting i at 0. Therefore the first test is if(array[0] == array[0]) ;)




回答3:


You're always going to get at least one error because array[0] == array[i] will be true on the first iteration, when i = 0.




回答4:


In your code at

int i=0;
for(i=0;i<size;i++){
    if(array[0]==array[i]){    //this condition runs true only for the first time. as i=0 here
        error=error+1;
    }
    System.out.println(error); //now here you had put the println(error) outside the if()-condition therefore it will be printed repeatedly value of error which is 1
}



回答5:


Try a doubly nested for loop. Something like this

for (int i=0;i<size-1;i++){
  for (int j=i+1; j<size; j++) {
    error += (array[i] == array[j]) ? 1 : 0;
  }
}



回答6:


You also need to "think Java". Use Array.equals for the comparison. See the documentation here and some examples here




回答7:


If you are going to make use of any collection, you can easiy findout the duplicates in the array

Example:

 public static void main(String[] args) {
    boolean containsDuplicate =false;
    int[] intArray = new int[] {1,245,324,1,523};
    List<Integer> myObj = new ArrayList<Integer>();
    for(int id : intArray){
        if(myObj.contains(id)){
            containsDuplicate = true;
            System.out.println("Duplicate");
        }else{
            myObj.add(id);
        }
    }

}



回答8:


Following code is fine but it returns 11. Not sure if it is what was expected.

public static void main(String[] args){
    int[] array = {23, 23, 0, 43, 545, 12, -55, 43, 12, 12, -999, -87, 12, 0, 0};
    int error = 0;
    for(int i=0;i<array.length;i++){
        for(int j=i+1;j<array.length;j++){
            if(array[i] == array[j]){
                if(i!=j){
                    error = error + 1;
                }
            }
        }
    }
    System.out.println(error);
}

I propose little bit complicated but hopefully more advanced solution.

package myjavaprogram;
import java.util.Arrays;

public class TestClass1 {
    public static void main(String[] args){
        int[] array = {23, 23, 0, 43, 545, 12, -55, 43, 12, 12, -999, -87, 12, 0, 0};
        //int[] array = {23, -22, 0, 43, 545, 12, -55, 43, 12, 0, -999, -87, 12};
        //int[] array = {23, -22, 0, 23};
        //int[] array = {23, -22, 23};
        calculate_duplicates(array);        
    }

    private static void calculate_duplicates(int[] array) {
        calculateUniqueNumbers(array);
    }

    private static void calculateUniqueNumbers(int[] array) {
        Pair[] pairs = new Pair[array.length];
        initializePairsAtrray(pairs, array);
        printPairsAtrray(pairs);

        System.out.println("array.length="+array.length);
        System.out.println("--------------------");

        // update pairs array taking in account duplicates duplicates
        for(int i = 0; i < array.length; i++) {
            System.out.println("array[i]="+array[i] + " i="+i);
            for(int j = i+1; j < array.length; j++) {
                System.out.println("array[j]="+array[j]+" j="+j);

                if(array[i] == array[j] && pairs[j].useDuringCount == true) {
                    pairs[i].occurance_num++;

                    pairs[j].occurance_num = 0;
                    pairs[j].useDuringCount = false;
                }

                if(array[i] == 0) {
                    pairs[i].occurance_num = 0;                    
                }
                if(array[j] == 0) {
                    pairs[j].occurance_num = 0;
                    pairs[j].useDuringCount = false;
                }                
            }
            pairs[i].useDuringCount = false;
            System.out.println("--------------------");
        }                
        printPairsAtrray(pairs);

        // calculate general number of duplicates (numbers whick are repeated 
        // in initial array)
        System.out.println("Duplicates in array:"+
                calculateDuplicatesNumber(pairs));        
    }

    private static void initializePairsAtrray(Pair[] pairs, int[] array) {
        for(int i=0;i<pairs.length;i++) {
            Pair p = new Pair();            
            p.occurance_num = 1;
            p.value = array[i];
            p.useDuringCount = true;
            pairs[i] = p;
        }
    }

    private static void printPairsAtrray(Pair[] pairs) {
        System.out.println("--------------------");
        for(int i=0;i<pairs.length;i++) {
            System.out.println("pairs["+i+"].occurance_num="+pairs[i].occurance_num);
            System.out.println("pairs["+i+"].value="+pairs[i].value);
            System.out.println("pairs["+i+"].useDuringCount="+pairs[i].useDuringCount);
            System.out.println("--------------------");
        }
    }

    private static int calculateDuplicatesNumber(Pair[] pairs) {
        System.out.println("-------------------- Duplicates:");
        int duplicates_num = 0;
        for(int i=0;i<pairs.length;i++) {
            if(pairs[i].occurance_num > 1) {
                duplicates_num++;
                System.out.println("number: "+pairs[i].value+" occurance_num " + pairs[i].occurance_num);
            }
        }
        return duplicates_num;
    }        
}    

class Pair {
    int value;
    int occurance_num;
    boolean useDuringCount;
}

Mykola



来源:https://stackoverflow.com/questions/7604683/finding-duplicates-in-java-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!