PDA

Click to See Complete Forum and Search --> : duplicate elements in an array.


Magnus_Lei
May 16th, 2003, 02:47 PM
Im needing help. I am trying to get the duplicate elements out of an array.

This is what i got so far...
public class test
{
public static void main(String args[])
{
int[] iarray={1, 4, 4, 4, 5};

int value = iarray.length;
for(int i=0; i<value; i++)
{ System.out.println("first for" + iarray[i]);
int num=iarray[i];
for(int j=i+1; j<value; j++)
{
System.out.println("second for" + iarray[j]);
if (num==iarray[j]){
for(int k=j; k<value; k++)
iarray[j]=iarray[j+1];
value--;}

}
}

System.out.println("Array now");
for(int i=0; i<iarray.length; i++)
{
System.out.print(iarray[i]+", ");
}
System.out.println();
}
}

So for instance i want to take out all the 4's except for one of them.
Any help would be appreciated.

Mag

CornedBee
May 17th, 2003, 05:20 AM
First, use tags when posting code.
Second, you can use a BitSet or some other Set to keep track of the numbers that already occurred and leave them out.
If the numbers are guaranteed to be low (up to ~200) a BitSet is better, if they get higher you should use a TreeSet or HashSet.

And you can't modify an array in place, you need to create a new array that you fill with the values. I recommed an ArrayList, and as last action copying the values back to a new array.