Java 集合知识总结(二)

Set集合
Set和Collection基本相同,Set不允许有重复元素,集合内的元素是无序的。
1) HashSet类
特点:不能保证元素的排列顺序、不是同步的,多线程操作时需要通过代码保证其同步性、集合元素值可以为null。HashSet添加原始的时候根据元素的hashCode值来计算 它的存储位置,方便快速该元素。(hash算法的功能是保证快速查找被检索的对象,根据元素的hashcode值计算该元素的存储位置,从而快速定位元素位置。)
HashSet判断元素是否相等通过equals()方法相等,并且hashCode()方法返回值也必须相等。
代码示例:

 

/**
 * 重写equals方法,不重写hashcode方法
 * @author Administrator
 *
 */
public class Demo1 {
   @Override
   public boolean equals(Object obj) {
      return true;
   }
}
 
/**
 * 重写hashcode方法,不重写equals方法
 * @author Administrator
 *
 */
public class Demo2 {
   @Override
   public int hashCode() {
      return 1;
   }
}
 
/**
 * 重写equals方法和hashcode方法
 * @author Administrator
 *
 */
public class Demo3 {
   @Override
   public boolean equals(Object obj) {
      return true;
   }
   @Override
   public int hashCode() {
      return 2;
   }
}
 
public class HashSetDemo {
   public static void main(String[] args) {
      HashSet ss = new HashSet();
 
      // 插入equals方法相等的两个对象
      ss.add(new Demo1());
      ss.add(new Demo1());
 
      // 插入hashcode相等的两个对象
      ss.add(new Demo2());
      ss.add(new Demo2());
 
      // 插入equals和hashcode相等得对象
      ss.add(new Demo3());
      ss.add(new Demo3());
 
      // 输出结果
      System.out.println(ss);
   }
}

 

输出结果是:

[com.zzl.demo.Demo2@1, com.zzl.demo.Demo2@1, com.zzl.demo.Demo3@2, com.zzl.demo.Demo1@565dd915, com.zzl.demo.Demo1@2b571dff]

上述输出结果表示HashSet判断元素相等必须equals方法和hashcode方法返回值必须相等,如demo3类

HashSet基本使用代码示例:

 

public class HashSetTest {
   public static void main(String[] args) {
      Set<String> hashSet = new HashSet<String>();
 
      // 添加元素
      hashSet.add("Set集合");
      hashSet.add("List集合");
      hashSet.add("Map集合");
 
      // 删除元素
      hashSet.remove("Map集合");
 
      // 遍历元素
      for (String string : hashSet) {
         System.out.println(string);
      }
 
      Iterator<String> iter = hashSet.iterator();
      while (iter.hasNext()) {
         String str= (String) iter.next();
         System.out.println(str);
      }
   }
}

2)TreeSet类

特点:使用红黑树结构存储元素、元素是有序的、支持两种排序方法,自然排序和定制排序,treeSet只能添加一种类型的对象存储元素时对象必须重写Comparable接口中得compareTo(Object obj)方法,否则引发ClassCastException异常。TreeSet集合判断两个对象是否相等,是通过compareTo(Object obj)方法比较是否返回0,返回0则相等,否则则不相等。

 

public class Test{
}
 
public class TreeSetTest {
   public static void main(String[] args) {
      Set treeSet = new TreeSet();
      treeSet.add(new Test());
      treeSet.add(new Test());
      System.out.println(treeSet);
   }
}

 

输出结果:

 

Exception in thread "main" java.lang.ClassCastException: com.zzl.demo.Test cannot be cast to java.lang.Comparable
   at java.util.TreeMap.compare(Unknown Source)
   at java.util.TreeMap.put(Unknown Source)
   at java.util.TreeSet.add(Unknown Source)
   at com.zzl.demo.TreeSetTest.main(TreeSetTest.java:10)

 

总结:因为TreeSet需要额外的红黑树算法来维护元素的次序,所以TreeSet的性能不如HashSet;当需要保持排序的Set时,使用TreeSet,否则建议使用HashSet

 

posted on 2017-07-09 15:02  若离  阅读(150)  评论(0编辑  收藏  举报

导航