使用下面的方法头编写方法,消除数组中重复出现的值:
public static int[] eliminateDuplicates(int[] list)
编写一个测试程序,读取10个数,调用该方法,并显示以一个空格分隔的不同数字。
package pack2; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Scanner; import java.util.Set; public class Eliminate { public static void main(String[] args) { try(Scanner input = new Scanner(System.in);) { int[] list = new int[10]; System.out.print("Enter ten numbers: "); for (int i = 0; i < list.length; i++) list[i] = input.nextInt(); System.out.print("The distinct numbers are:"); for (int i : eliminateDuplicates(list)) { if(i != 0) System.out.print(" "+i); } } } /**消除重复*/ public static int[] eliminateDuplicates(int[] list) { Set<Integer> set = new LinkedHashSet<>(); //创建链式散列集(存储不重复的值) for (int i : list) //遍历数组,添加元素到集合中 set.add(i); int[] temp = new int[set.size()]; int index = 0; for (Integer i : set) //遍历集合,赋值给临时数组 temp[index++] = i; return temp; } }