0

I had the following idea to take an array and remove any duplicates. However, I am getting the error "error: incompatible types: cannot be converted to int" referring to the part of the code where I set temp[i] = null. Is it possible to do this? How can I fix this problem?

public static int[] withoutDuplicates(int[] x) {
    int[] temp = new int[x.length];
    int count = 0;
    for (int i = x.length - 1; i >= 0; i--) {
      for (int j = i-1; j >= 0; j--) {
        if (temp[i] == x[j]) {
          temp[i] = null;
          count++;
        }
      }
    }
    int size = x.length - count;
    int[] a = new int[size];
    int pos = 0;
    for (int i = 0; i < x.length; i++) {
      if (temp[i] != null) {
        a[pos] = temp[i];
        pos++;
      }
    }
    return a;
  }
1
  • 2
    null is a reference, while int is a primitive type. You cannot assign a reference to a primitive. Use Integer instead of int Commented Oct 9, 2020 at 20:06

2 Answers 2

1

Stream-based solution is concise but for your task/requirements you could be using just a temporary boolean array to mark positions of duplicates:

public static int[] withoutDuplicates(int[] x) {
    boolean[] duplicated = new boolean[x.length];
    int count = 0;
    for (int i = x.length - 1; i > 0; i--) {
        for (int j = i-1; j >= 0; j--) {
            if (x[i] == x[j]) {
                duplicated[i] = true;
                count++;
             }
        }
    }
    int size = x.length - count;
    int[] a = new int[size];
    for (int i = 0, pos = 0; pos < size && i < x.length; i++) {
        if (!duplicated[i]) {
            a[pos++] = x[i];
        }
    }
    return a;
}

Test:

int[] arr1 = {1, 2, 3, 4, 3, 5, 2};
int[] arr2 = {1, 2, 3, 4, 0, 5, 6};
        
System.out.println(Arrays.toString(withoutDuplicates(arr1)));
System.out.println(Arrays.toString(withoutDuplicates(arr2)));

output

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 0, 5, 6]
Sign up to request clarification or add additional context in comments.

Comments

1

You can't assign a null to a primitive type int but you can assign a null to the wrapper object Integer.

To remove the duplicates of an int array you could use something like this:

myIntArray = Arrays.stream(myIntArray).distinct().toArray();

1 Comment

Java 14 needed? Java ≥ 8 is sufficient.

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.