# Removing Duplicates in an Array

• 02-01-2012, 02:45 AM
jerseyjava
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:

Code:

``` public class arrays1 {     public static void main(String[] arg)     {                         int[] Array = new int[20];                                 readIn(Array);                                 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);         } } }```
• 02-01-2012, 03:24 AM
Norm
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?
• 02-01-2012, 03:31 AM
jerseyjava
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.
• 02-01-2012, 03:40 AM
diamonddragon
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
• 02-01-2012, 03:58 AM
Norm
Re: Removing Duplicates in an Array
Quote:

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.
• 02-01-2012, 04:14 AM
kjkrum
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.
• 02-01-2012, 04:36 AM
Norm
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.
• 02-01-2012, 08:46 PM
j2me64
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.