- set集合接口也属于Collection的常用接口,其最大特点是不允许出现重复数据。
- TreeSet中是有序的容器,所以如果将散乱的set集合中的元素放入到TreeSet中,那么会自动排好序。(前提是放入的元素的类实现了Comparable接口)
- hashset只能增删不能改查,set就像一个集合一样,没有角标,所以不能定位元素(像茶壶煮饺子到倒不出来),而且hashset是根据散列hash存储元素的,所以看起来是无序的。
1、增
- add();
- addAll(Collection);
public static void main(String[] args) {
List<String> list = new LinkedList<>();
list.add("hello");
list.add(0, "world");
list.add("MLDN");
list.add("www.mldn.cn");
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("F");
set.addAll(list);
System.out.println(set);
}
这里可以了解一下TreeSet,TreeSet是一个有序集合,即使在插入的时候没有顺序,那么在输出的时候就是都会是有序的了。但是使用TreeSet的时候,插入的对象要是实现了Comparable接口才可以正常使用。
2、删
- remove(T t); 根据元素内容删除元素
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("F");
System.out.println(set);
System.out.println(set.remove("A"));
}
3、遍历
1、for-each遍历
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("F");
for (String s : set) {
System.out.println(s);
}
}
2、迭代器遍历
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("F");
Iterator<String> i = set.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}