Remove duplicate elements: Difference between revisions
→{{header|Java}}
Line 2,955:
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.
import java.util.
import java.util.List;
import java.util.Set;
</syntaxhighlight>
One way would be to add the values to a ''Set'' object, which only allows for unique values.
<syntaxhighlight lang="java">
int[] removeDuplicates(int[] values) {
/*
for (int
for (int index = 0; index < 20; index++)▼
array[index] = random.nextInt(1, 5);▼
Set<Integer> set = new HashSet<>();▼
for (int value : array)▼
set.add(value);
while (iterator.hasNext())
return values;
}
</syntaxhighlight>
Alternately, you could simply add the values to a mutable ''List'', checking if the list already contains the value before adding it.
<syntaxhighlight lang="java">
int[] removeDuplicates(int[] values) {
for (int
array[index] = random.nextInt(1, 5);▼
if (!list.contains(value)) list.add(value);
int index = 0;
return values;
}
</syntaxhighlight>
<pre>
</pre>
<br />
|