Results 1 to 2 of 2
  1. #1
    hacikho is offline Member
    Join Date
    Sep 2009
    Rep Power

    Default remove duplicates in array gives wrong result

    I have a char array, and in this array I want to remove repeating element I try below code unfortunately there is something wrong, it removes duplicates but it also duplicate last element. Array elements are 'A','C','C','D' but after I applied blow code I got 'A','C','D','D' on result, but I should get 'A','C','D' . can you look at the code and tell me the problem

    Java Code:
       int NewLength = 1;
            int i,j;
            for(i=1; i< LHSArray.length; i++)
               for(j=0; j< NewLength ; j++)
                   if(LHSArray[i] == LHSArray[j])
               if (j==NewLength )
                  LHSArray[NewLength++] = LHSArray[i];

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Rep Power

    Default Re: remove duplicates in array gives wrong result

    Remember that arrays have a fixed length. You cannot "chop off" the last element. you have 2 options: keep a counter that holds the number of desired elements in the array and only print out that many values. Or make a new smaller array and copy across only the desired elements.

Similar Threads

  1. Remove Duplicates in Array
    By HSKrustofsky in forum New To Java
    Replies: 11
    Last Post: 09-06-2011, 05:47 AM
  2. Remove duplicates in 2D array
    By lakshmibvaraprasad in forum New To Java
    Replies: 5
    Last Post: 07-22-2011, 08:49 PM
  3. New To Java - Input Number Won't Prompt, Wrong Result
    By jhuwalker in forum New To Java
    Replies: 2
    Last Post: 01-31-2011, 10:29 PM
  4. Duplicates in String Array
    By turnergirl24 in forum New To Java
    Replies: 1
    Last Post: 11-04-2009, 11:09 PM
  5. FInd the no. of duplicates in an array
    By singularity in forum Advanced Java
    Replies: 3
    Last Post: 09-04-2009, 09:25 AM

Posting Permissions

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