Write a Java program to remove the duplicate elements of a given array and return the new length of the array.
Question
Write a Java program to remove the duplicate elements of a given array and return the new length of the array.
Solution
Here is a simple Java program that removes duplicate elements from an array and returns the new length of the array. This program uses a HashSet, which does not allow duplicate elements.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 2, 3, 4, 4, 5, 6, 6, 7};
int newLength = removeDuplicates(array);
System.out.println("The new length of the array is: " + newLength);
}
public static int removeDuplicates(int[] array) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < array.length; i++) {
set.add(array[i]);
}
return set.size();
}
}
In this program, we first initialize an array with some duplicate elements. We then call the removeDuplicates
method, which takes this array as an argument. Inside this method, we create a HashSet and add all elements of the array to this set. Since a set does not allow duplicate elements, all duplicates are automatically removed. Finally, we return the size of the set, which is the new length of the array without duplicates.
Similar Questions
which function is used to remove duplicate values from an array?Select one:a.array_single()b.array_unique()c.array_remove()d.array_rem_repeat(
Select the correct answerHow can you find the length of an array myArray in Java?OptionsmyArray.size( );myArray.length;myArray.size;myArray.count;
Write a java method to reverse the elements of an array using recursion. Your method should take an array as an input parameter and return reverse the array
Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.
Which ArrayList method is used to remove the first occurrence of a specific element from the list?Question 3Answera.delete()b.removeFirst()c.erase()d.remove()
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.