# Thread: Removing Duplicates in an Array

1. Member
Join Date
Feb 2012
Posts
2
Rep Power
0

## Removing Duplicates in an Array

I have an assignment to: Create an array of 20 random numbers (1-15000). It has to print the original list (on one line), and Eliminate the duplicates then reprint list.

What I have got up to so far is generating the random numbers in an array, but thats where I get stuck. I dont know how to get rid of the duplicates.

Here's my code so far:

Java Code:
```public class arrays1
{
public static void main(String[] arg)
{

int[] Array = new int[20];

for(int i=0; i<20; i++) {
System.out.println("Array will contain "+Array[i]);
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*15000+1);
}
}
}```
Last edited by jerseyjava; 02-01-2012 at 02:47 AM.

2. ## Re: Removing Duplicates in an Array

What do you mean by "get rid of"?
Arrays are static. They don't change in size.
What will the resulting array look like? Size and contents.

Given an array: 2, 3, 4, 3
How would you manually remove a duplicate? Say you can only see two numbers at a time, what are the steps you would take?

3. Member
Join Date
Feb 2012
Posts
2
Rep Power
0

## Re: Removing Duplicates in an Array

This is what I am unsure of. And by getting rid of I meant to say, that I want to know how to take the array list of random number and be able to make it so that the duplicates are not displayed.

4. Senior Member
Join Date
Jan 2012
Posts
210
Rep Power
6

## Re: Removing Duplicates in an Array

Here is one idea how to do it, but I'm leaving You to code it:
-Make loop through array, say variable i
-Take one number from array at i-th index and find if exist in array (i+1, i+2,...,i+n)
----If exist, leave it
----If don't exist, use it
Last edited by diamonddragon; 02-01-2012 at 03:43 AM.

5. ## Re: Removing Duplicates in an Array

make it so that the duplicates are not displayed.
How is the contents of the array being displayed?
Are you going to write a loop to display the numbers and skip over displaying the duplicates?
Say the array's contents is: 1,2,1,3
Your display program would display the 1 2 and 3 and not display the extra 1.
You would need some way to tell the display program to skip over the element at index 2.

That's not really removing a duplicate.

6. ## Re: Removing Duplicates in an Array

Have you been taught about Collections yet? I'd create a Set<Integer> and put the numbers into it.

7. ## Re: Removing Duplicates in an Array

@kjkrum I suspect that won't be taught for another few weeks. This exercise is on how to index into arrays. A very necessary skill.

8. ## Re: Removing Duplicates in an Array

sort your list with Arrays.sort(List) and when printing the elements one by one if the actual element is the same like the last one skip it.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•