package Package;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
in.nextToken();
int N = (int)in.nval;
HashSet<Integer> hs=new HashSet<Integer>();
for(int i=0; i<N; i++) {
in.nextToken();
hs.add((int)in.nval);
}
ArrayList<Integer> al=new ArrayList<Integer>();
al.addAll(hs);
Collections.sort(al);
out.print(al.size()+"\n");
Iterator<Integer> it = al.iterator();
while(it.hasNext()) {
out.print(it.next()+" ");
}
out.flush();
out.close();
}
}
一、创建HashSet对象并添加元素,目的:去重
创建对象:
HashSet<Integer> hs=new HashSet<Integer>();
添加元素:
hs.add((int)in.nval);
二、创建ArrayList对象并添加元素,目的:排序
创建对象:
ArrayList<Integer> al=new ArrayList<Integer>();
将HashSet对象转化为ArrayList对象元素:
al.addAll(hs);
三、创建Iterator对象并迭代输出
创建对象:
Iterator<Integer> it = al.iterator();
循环输出元素:
while(it.hasNext()) {
out.print(it.next()+" ");
}
四、直接用TreeSet
package Package;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
in.nextToken();
int N = (int)in.nval;
TreeSet<Integer> ts=new TreeSet<Integer>();
for(int i=0; i<N; i++) {
in.nextToken();
ts.add((int)in.nval);
}
out.print(ts.size()+"\n");
Iterator<Integer> it = ts.iterator();
while(it.hasNext()) {
out.print(it.next()+" ");
}
out.flush();
out.close();
}
}