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

How to Correctly Identify Duplicates in a Java Array?

DDD
Release: 2024-12-07 22:19:13
Original
1093 people have browsed it

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;
        }
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template