一、HashSet集合
1.HashSet集合的特点

2.HashSet常用方法
①:add(Object o):向Set集合中添加元素,不允许添加重复数据。
②:size():返回Set集合中的元素个数
③.remove(Object o): 删除Set集合中的obj对象,删除成功返回true,否则返回false。
④.isEmpty():如果Set不包含元素,则返回 true。
⑤.clear(): 移除此Set中的所有元素。
⑥.iterator():返回在此Set中的元素上进行迭代的迭代器。
⑦.contains(Object o):判断集合中是否包含obj元素。
⑧:加强for循环遍历Set集合:
二、LinkedHashSet集合
LinkedHashSet集合的特点

三、TreeSet集合
1.TreeSet集合的特点

2.TreeSet的基本使用
①.插入是按字典序排序的
public class Test {
public static void main(String[] args) {
TreeSet ts=new TreeSet();
ts.add("agg");
ts.add("abcd");
ts.add("ffas");
Iterator it=ts.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
输出 : 按照字典序排序的方式进行排序
abcd agg ffas
②.如果插入的是自定义对象 需要让类实现 Comparable 接口并且必须要重写compareTo
class Person implements Comparable{
String name;
int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
@Override
public int compareTo(Object o) {
Person p=(Person)o;
//先对姓名字典序比较 如果相同 比较年龄
if(this.name.compareTo(p.name)!=0) {
return this.name.compareTo(p.name);
}
else
{
if(this.age>p.age) return 1;
else if(this.age<p.age) return -1;
}
return 0;
}
}
public class Test {
public static void main(String args[])
{
TreeSet ts=new TreeSet();
ts.add(new Person("agg",21));
ts.add(new Person("abcd",12));
ts.add(new Person("ffas",8));
ts.add(new Person("agg",12));
Iterator it=ts.iterator();
while(it.hasNext())
{
Person p=(Person)it.next();
System.out.println(p.name+":"+p.age);
}
}
}
输出
abcd:12 agg:12 agg:21 ffas:8
四、HashSet、LinkedHashSet、TreeSet的使用场景
HashSet:HashSet的性能基本上比LinkedHashSet和TreeSet要好,特别是添加和查询,这也是用的最多的两个操作
LinkedHashSet:LinkedHashSet的查询稍慢一些,但是他可以维持元素的添加顺序。所以只有要求当插入顺序和取出顺序一致的时候 才使用LinkedHashSet。
TreeSet:只有在需要对元素进行排序时使用
五、list和set集合的区别
