0基础学java_Java类集之Set接口

Set接口

Set接口是collection接口的子接口,但是与collection接口和list接口不同的是set接口不能加入重复元素。Set接口无法向list接口那样进行双向输出,Set接口常用子类,散列存放HashSet,有序存放TreeSet

举例:重复向hashSet中加入元素

 1 package com.feimao.a1;
 2 
 3 
 4 
 5 import java.util.HashSet;
 6 
 7 
 8 
 9 public class HashSetDemo01 {
10 
11     public static void main(String args[]) {
12 
13         HashSet<String> h = new HashSet<String>();
14 
15         h.add("A");
16 
17         h.add("B");
18 
19         h.add("C");
20 
21         h.add("C");
22 
23         h.add("C");
24 
25         h.add("D");
26 
27         h.add("E");
28 
29         System.out.println(h);
30 
31 
32 
33 
34 
35     }
36 
37 }

举例:TreeSet子类可以排序

 1 package com.feimao.a1;
 2 
 3 
 4 
 5 import java.util.HashSet;
 6 
 7 import java.util.TreeSet;
 8 
 9 
10 
11 public class HashSetDemo01 {
12 
13     public static void main(String args[]) {
14 
15         TreeSet<String> t = new TreeSet<String>();
16 
17         t.add("F");
18 
19         t.add("B");
20 
21         t.add("C");
22 
23         t.add("C");
24 
25         t.add("A");
26 
27         t.add("D");
28 
29         t.add("E");
30 
31         System.out.println(t);
32 
33 
34 
35 
36 
37     }
38 
39 }

猜你喜欢

转载自www.cnblogs.com/feimaoyuzhubaobao/p/9949997.html