Set

来源:互联网 发布:个人网站域名后缀 编辑:程序博客网 时间:2024/05/22 08:29
1、Set
A collection that contains no duplicates elements.
2、How to judge whether an element is  duplicate?
      1)This is HashSet's main code to judge whether duplicate or not.

    public boolean containsKey(Object key) {          
        return getEntry(key) != null;
     }
final Entry<K,V> getEntry(Object key) {
         int hash = (key == null) ? 0 : hash(key.hashCode());
         for (Entry<K,V> e = table[indexFor(hash, table.length)];
              e != null;
              e = e.next) {
             Object k;
             if (e.hash == hash &&
                 ((k = e.key) == key || (key != null && key.equals(k))))
                 return e;
         }
         return null;
    }
       
        2)二元素为同一个元素必要条件
                (1)、hash值相同
          (2)、== 或者 equals相同

 3、案例分析
        假如保存学生信息,但有可能添加重复添加,可以考虑是Set进行去重。
        eg:用Student类封装学生信息
        class Student
{
     private String name;
     private int age;
    
     public Student(String name,int age)
     {
     this.name = name;
     this.age = age;
     }
     public String getName()
     {
     return name;
     }
     public int getAge()
     {
     return age;
     }
}

public class HashSetDemo {
     public static void main(String args[])
     {
     Set<Student> stu_set = new HashSet<Student>();
    
     Student s1 = new Student("DLH",22);
     Student s2 = new Student("DLH",22);
    
     stu_set.add(s1);

if(stu_set.contains(s1))
{
System.out.println("集合中已包含DLH");
}
else
{
System.out.println("集合中尚未包含DLH");
}

if(stu_set.contains(s2))
{
System.out.println("集合中已包含DLH");
}
else
{
System.out.println("集合中尚未包含DLH");
}
     }

 }

输出结果是:
集合中已包含DLH
**********************************
集合中尚未包含DLH
显然可以解决同一个对象添加二次的情况,但是不能保证同样内容的信息只添加一次。下面根据Set中判断重复的原则,进行完善,修改 Student类
  class Student
{
     private String name;
     private int age;
    
     public Student(String name,int age)
     {
     this.name = name;
     this.age = age;
     }
     public String getName()
     {
     return name;
     }
     public int getAge()
     {
     return age;
     }
    
     @Override
     public boolean equals(Object obj)
     {
     //根据姓名判断是否相同
     Student stu = (Student)obj;
     boolean flag = stu.getName().equals(this.name);
     return flag;
     }

@Override
public int hashCode()
{
//利用字符串值的hash值
return this.name.hashCode();
}
}

完善后输出结果为:
集合中已包含DLH
************************
集合中已包含DLH
显然可以达到去重的效果Set - shutear - shutear

4、List与Set 的主要区别
List可以包含重复的元素、而Set不能(重复判断标准见2-2) ).
原创粉丝点击