Java How To Find Duplicates in an Array
Find Duplicate Elements in an Array
Print which elements appear more than once:
Example
int[] nums = {1, 2, 3, 2, 4, 5, 1};
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
System.out.println("Duplicate: " + nums[i]);
}
}
}
Explanation:
We go through the array one element at a time.
- The outer loop picks a number (like the first 1
).
- The inner loop compares it with all the numbers that come after it.
- If a match is found, we print it as a duplicate.
In this example, the program finds 2
twice and 1
twice, so it prints them as duplicates.