I am new to Java, and I am in a class where for the homework, I need to remove duplicate elements in an array, but I have come across an obstacle in my code:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot invoke remove(int) on the array type int[] at File10.main(File10.java:17)
This is my code so far:
import java.util.ArrayList; public class Homework10 { public static void main(String[] args) { int arrayLength = (int) (Math.random()*50); int[] randomArray = new int[arrayLength]; for (int i =0; i<arrayLength; i++) { randomArray[i] = (int) (Math.random()*20); } System.out.println("Original Array:"); for (int i =0; i<arrayLength; i++) { System.out.print(randomArray[i] + " "); } for (int i =0; i<randomArray.length; i++) { for (int k =(i + 1); k<randomArray.length; k++) { if (randomArray[i] == randomArray[k]) { randomArray.remove(k); } } } } }
Everything I have checked either does not relate to my code or proves that there shouldn’t be an error in my code.
Advertisement
Answer
There is no remove()
method on an array. Use an ArrayList, or read the api on arrays.