Set集合:
set接口是Collection的子接口,set接口中容器的元素是没有顺序的,并且不可以重复。
set集合下有HashSet和TreeSet两个子接口,HashSet的数据结构是哈希表,线程是非同步的,里面的元素必须是不同的,从而保证了元素的唯一性。
唯一性原理:java虚拟机首先会判断集合中的hashCode是否相同,如果相同,继续判断元素的equals方法,当equals方法和HashCode都一样时,则该集合元素是唯一的。
自定义对象时,需要实现Comparable接口,同时要改写comapareTo方法,因为在Set集合中元素会依次进行比较,而String方法天生就改写了compareTo方法,所以可以用compareTo方法进行字符串的比较,从而保证集合中的元素的完全性和唯一性。
代码实现如下:
public class lpq01{
public static void main(String []arsg){
Collection c=new TreeSet();//利用多态
c.add(new Student("lpa09",18));//向容器中添加元素
c.add(new Student("lpq08",22));
c.add(new Student("lpq11",18));
c.add(new Student("lpq23",24));
Iterator it=c.iterator();//迭代器循环遍历每一个元素
while(it.hasNext()){
Student stu=(Student)it.next();//next属于Object对象所以放强制转型为Student对象
System.out.println(stu.getName()+" "+stu.getAge());
}
}
}
class Student implements Comaparable {
private String name;
private int name;
public int compareTo(Object obj){
if(!(obj instanceof Student))
return new RuntimeExceptin("不是学生对象!");
Student s=(Student)obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)//如果年龄相等在判断名字是否一样;
{
return this.name.compareTo.(s.name);//String方法天生(封装)改写了compareTo方法
}
return 0;
}
public Student(String name,int age){
this.name=name;
this,age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}