java消除整型数组中重复的元素,排序后输出新数组

时间:2022-06-04 03:15:40

法一:

import java.util.Arrays;
import java.util.Scanner; public class Main
{
public static void main(String[] args)
{
int[] a = new int[50];
Scanner scanner = new Scanner(System.in);
int index = 0;
String x;
while(!(x=scanner.nextLine()).equals(""))
{
a[index++] = Integer.parseInt(x);
}
Arrays.sort(a,0,index);
int k = 0;
for(int i = 0;i<index;i++)
{
if(a[k]!=a[i]) {
a[++k] = a[i];
}
}
for(int i = 0;i<k+1;i++)
{
System.out.print(a[i]+" ");
}
scanner.close();
}
}

输入输出如下:

1

2

2

4

5

4

3

1 2 3 4 5

法二:

使用集合(自动排序去重)

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set; public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String x;
Set<String> set = new HashSet<String>();
while(!(x=scanner.nextLine()).equals(""))
{
set.add(x);
}
String[] a = new String[set.size()];
set.toArray(a);
for(int i = 0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
scanner.close();
}
}

输入输出如下:

1

2

3

2

4

2

3

5

1 2 3 4 5