set集合特点级子类的特点

来源:互联网 发布:mmd古风动作数据 编辑:程序博客网 时间:2024/04/27 20:45

Set集合,无序,不可以重复元素

Set集合中的子类HashSet和TreeSet集合的特点

首先说一下HashSet:  数据结构是哈希表。线程是非同步的。

保证元素唯一性的原理:判断元素的hashCode值是否相同

如果相同,还会继续判断元素的equals方法,是否为true.


TressSet : 可以对Set集合中的元素进行排序。
底层数据结构是二叉树,
保证元素唯一性。
TreeSet排序的第一中方式:让元素自身具备比较性
元素需要实现Complare    

注意:当主要条件相同时,一定要判断次要条件

上代码:

import java.util.*;
class TreeSetDemo 
{
public static void main(String[] args) 
{
TreeSet ts=new TreeSet();
ts.add(new Student("学生1",22));
ts.add(new Student("学生2",20));
ts.add(new Student("学生3",20));
ts.add(new Student("学生4",40));
Iterator it=ts.iterator();
while(it.hasNext())
{
Student stu=(Student)it.next();
System.out.println(stu.getName()+"...."+stu.getAge());
}
}
}


class Student implements Comparable//该接口强制让学生具备比较性。
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student s=(Student)obj;
System.out.println(this.name+"...compareto..."+s.name);
if(this.age>s.age)
return 1;
if(this.age==s.age)
{
return this.name.compareTo(s.name);//当主要条件满足判断次要条件
}

return -1;
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}}


0 0
原创粉丝点击