-2

I need to remove duplicate elements from an array by adding elements that are not repeated in the original array to a new array and output the contents of that.

The problem I am having is that when the new array with no duplicates is printed there are zeros being outputted also.

Thus: does Java fill the array with zeros?

public static boolean hasDuplicates(int arrayNum[])
    {
        boolean dupFound = false;
        int ctr1 =0;

        while (ctr1<arrayNum.length && !dupFound)
        {
            int ctr2 = ctr1+1; // be 1 ahead each time ctr1 increments
            while(ctr2<arrayNum.length)
            {
                if(arrayNum[ctr1] == arrayNum[ctr2])
                    dupFound = true;
                ctr2++;
            }
            ctr1++;
        }       

        return dupFound;
    }

    public static int[] removeDuplicates(int[] arrayNum)
    {
        if(hasDuplicates(arrayNum) == false)
            return arrayNum;
        else
        {
            int outArray[] = new int[arrayNum.length]; 
            int ctr1=0;
            int ctr2 = ctr1+1;
            int index = 0;
            boolean dupFound = false;

            while(ctr1<arrayNum.length)
            {   
                dupFound = false;
                ctr2 = ctr1+1;

                while(ctr2<arrayNum.length && !dupFound)
                {
                    if(arrayNum[ctr1] == arrayNum[ctr2])
                        dupFound = true;
                    ctr2++;
                }

                if(dupFound == false)
                {
                    outArray[index] = arrayNum[ctr1]; 
                    index++;
                }

                ctr1++;
            }
            return outArray;
        }   
    }

    public static void testRemoveDuplicates()
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter size of input array");
        int array[] = new int[input.nextInt()];

        System.out.println("Enter number of ints required");
        for(int i=0; i<array.length; i++)
        {
            array[i] = input.nextInt();
        }

        int outArray[] = new int[array.length];
        outArray = removeDuplicates(array);
        for(int i=0; i<outArray.length; i++)
        {
            System.out.println(outArray[i]);
        }
    }
3
  • There's got to be something in the Collections package to do this... Commented Feb 27, 2017 at 18:14
  • Yes, Java arrays are initialized with all elements equal to zero. So in your case, creating a new array of the same size is going to give you some zeros if it does not supposed to contain some elements in the original array. Commented Feb 27, 2017 at 18:16
  • For the record: i guess there wont be much else coming; so please consider accepting the most helpful answer ... if that happens to be mine ... if that works for you: please wait until tomorrow with that ;-) Commented Feb 27, 2017 at 19:59

4 Answers 4

3

Here:

int outArray[] = new int[array.length];

That code assumes that you have exactly array.length array elements in your output array. And that is of course a too high number! The point is: when you create a new array of that size, the whole array is initially populated with 0 values. And your code will only "overwrite" a few slots of that output array; and all other slots stay at their initial 0 default value.

The point is: you first have to compute how many duplicates you have in your input array; and then you create a new array with exactly that number.

Alternatively, you could be using List<Integer> instead of int[]; as Java collections have the ability to grow dynamically. (or, you can keep increasing that array for collecting duplicates "manually"; that can be done, too - just a bit of complicated code to get there).

And the direct immediate answer is: yes, exactly - Java arrays are "pre-filled"; see here.

Sign up to request clarification or add additional context in comments.

Comments

1

You can fix all of your problems (and probably make the code substantially faster in the process since it'll no longer have quadratic complexity) by using standard Java API calls to store the unique elements in a Set, and then turn the values in that set back into an array.

The main caveat is that you'd need to use Integer rather than int:

Set<Integer> s = new LinkedHashSet<Integer>(Arrays.asList(inputArray));
Integer[] outputArray = s.toArray(new Integer[0]);

The LinkedHashSet preserves insertion order, so you'll get the elements back in the same order as they originally appeared albeit without the duplicates.

Comments

0

May be you are wasting too much memory here by considering the worst case scenario where all input given are different while declaring the output array size. More Optimized Approach is that you can have an List<Integer> or ArrayList<Integer> which can store the unique values and then at last , If you want unique values in Array than declare the ArraySize same as the ArrayList<Integer> or List<Integer> size and just in one linear loop , You can copy all the data.

Does Java fill the array with zeros?

Yes , Whenever you declare the integer array , It will be having all its elements as 0. If you want to reset the value of Array to a particular value , You can use this method Arrays.fill(int array[] , int default_value). This can be done in O(list_size) complexity which is linear.

For your purpose more better approach would be use of HashSet<Integer> which holds only unique elements and which is Dynamic in nature so no need to waste extra space as well as it can make your work very easy.

So first you need to all elements in the HashSet<Integer> and then by using Iterator you can easily iterate through it but the insertion order can be disturbed here. So as replied by @Alnitak You can use LinkedHashSet<Integer> to have insertion order same.

A sample code using HashSet :

HashSet<Integer> set=new HashSet<Integer>();

int total_inputs=sc.nextInt();

for(int i=0;i<total_inputs;i++)
    set.add(sc.nextInt());

Iterator itr=set.iterator();

while(itr.hasNext())
   System.out.println((int)itr.next());

Note : Here input order will not be preserved.

Comments

0

Does Java fill the array with zeros?

Yes, java will initialize every element of your int array to 0. Therefore using arr.length will not work for you as it doesn't return the logical length of your array. You need to track the number of elements of your array yourself. The following line in your code has no meaning

int outArray[] = new int[array.length];

because outArray starts pointing to a different array as returned by your method removeDuplicates.

I need to remove duplicate elements from an array by adding elements that are not repeated in the original array to a new array

The easiest thing you can do is the following way:

In your method removeDuplicates,

  1. Find the highest number from the given input array, increment it by 1 and assign it to a variable.

int max = Arrays.stream(arrayNum).max().getAsInt() + 1;

  1. Modify your if block from

    if(arrayNum[ctr1] == arrayNum[ctr2])
      dupFound = true; 
    

    to

    if(arrayNum[ctr1] == arrayNum[ctr2]) {
      dupFound = true; 
      arrayNum[ctrl] = max;
      max++;
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.