Results 1 to 2 of 2

Thread: duplicate elements in an array.

  1. #1

    Thread Starter
    Lively Member
    Join Date
    May 2001
    Posts
    80

    duplicate elements in an array.

    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

  2. #2
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    First, use [code][/code] 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.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

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



Click Here to Expand Forum to Full Width