set集合的特点:无序,值唯一(不能存储重复的元素)。
过滤重复字符,结果无序:
HashSet<Character> set = new HashSet<Character>();
public static void main(String[] args) {
String s = "QWERTYUIOPPOIUYTRDFGHJKJUYT";
//过滤重复字符,结果无序
HashSet<Character> set = new HashSet<Character>();
for(int i = 0;i<s.length();i++) {
set.add(s.charAt(i));
}
System.out.println(set);
}
输出结果为:
[D, E, F, G, H, I, J, K, O, P, Q, R, T, U, W, Y]
过滤重复字符,结果有序:
LinkedHashSet<Character> set = new LinkedHashSet<Character>();
public static void main(String[] args) {
String s = "QWERTYUIOPPOIUYTRDFGHJKJUYT";
//过滤重复字符,结果有序
LinkedHashSet<Character> set = new LinkedHashSet<Character>();
for(int i = 0;i<s.length();i++) {
set.add(s.charAt(i));
}
System.out.println(set);
}
输出结果为:
[Q, W, E, R, T, Y, U, I, O, P, D, F, G, H, J, K]