Home >Java >javaTutorial >How to Correctly Identify Duplicates in a Java Array?

How to Correctly Identify Duplicates in a Java Array?

DDD
DDDOriginal
2024-12-07 22:19:131118browse

How to Correctly Identify Duplicates in a Java Array?

Java Array, Finding Duplicates

Your code doesn't work correctly as it sets duplicates to true when it finds a duplicate. However, it also sets duplicates to true when it compares an element with itself (zipcodeList[k] == zipcodeList[j] when j == k), which is not a duplicate.

To fix this, you need to modify the condition, so it checks if j != k before setting duplicates to true. Here's the corrected code:

duplicates = false;
for(j = 0; j < zipcodeList.length; j++){
    for(k = 0; k < zipcodeList.length; k++){
        if (j != k &amp;&amp; zipcodeList[k] == zipcodeList[j]){
            duplicates = true;
        }
    }
}

The above is the detailed content of How to Correctly Identify Duplicates in a Java Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn