要检测数组中的重复值,您需要将数组中的每个元素与所有其他元素进行比较,以防匹配。
为此,一种解决方案需要使用两个循环(嵌套),其中内部循环以i + 1开头(其中i是外部循环的变量),以避免重复。
Apache Commons提供了一个名为org.apache.commons.lang3的库,下面是向您的项目添加库的maven依赖项。
<dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> </dependencies>
该程序包使用此类的remove()方法提供了一个名为ArrayUtils的类,您可以删除检测到的给定数组的重复元素。
import java.util.Arrays;
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;
public class DeleteDuplicate {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
}
System.out.println("The array created is ::"+Arrays.toString(myArray));
for(int i=0; i<myArray.length-1; i++) {
for (int j=i+1; j<myArray.length; j++) {
if(myArray[i] == myArray[j]) {
myArray = ArrayUtils.remove(myArray, j);
}
}
}
System.out.println("Array after removing elements ::"+Arrays.toString(myArray));
}
}输出结果
Enter the size of the array that is to be created :: 6 Enter the elements of the array :: 232 232 65 47 89 42 The array created is :: [232, 232, 65, 47, 89, 42] Array after removing elements :: [232, 65, 47, 89, 42]