HashSet和TreeSet有什麼區別?

HashSet:
不能保證元素的排列順序,順序有可能發生變化
集合元素可以是null,但只能放入一個null
HashSet底層是採用HashMap實現的
HashSet底層是哈希表實現的

TreeSet:
Treeset中的數據是排好序的,不允許放入null值。
TreeSet是通過TreeMap實現的,只不過Set用的只是Map的key。
TreeSet的底層實現是採用二叉樹(紅-黑樹)的數據結構。

參考代碼: HashSetTest TreeSetTest TreeSetStudentTest

// Set的使用(不允許有重複的對象),可以是null,但只能放入一個null
public class HashSetTest {
	public static void main(String[] args) {
		HashSet<String> hashSet = new HashSet<String>();
		String a = new String("A");
		String b = new String("B");
		String E = new String("E");
		String F = new String("F");
		String c = new String("B");
		String h = null;
		String i = null;
		hashSet.add(a);
		hashSet.add(b);
		hashSet.add(E);
		hashSet.add(F);
		hashSet.add(h);
		hashSet.add(i);
		System.out.println("hashSet得長度:" + hashSet.size());
		
		// 元素B已經存在,插入時不在插入
		String cz = hashSet.add(c) ? "此對象不存在" : "已經存在";
		System.out.println("測試是否可以添加對象: " + cz);
		
		// 測試其中是否已經包含某個對象
		System.out.println("hashSet中包含A:" + hashSet.contains("A"));
		Iterator<String> iter = hashSet.iterator();
		while (iter.hasNext()) {
			System.out.println("hashSet中的元素:" + iter.next());
		}
		// 測試某個對象是否可以刪除
		System.out.println("刪除不存在的元素e:" + hashSet.remove("e"));
		System.out.println("刪除存在的元素E:" + hashSet.remove("E"));
		System.out.println();
		// 如果你想再次使用iter變量,必須重新更新,重新獲取
		iter = hashSet.iterator();
		while (iter.hasNext()) {
			System.out.println("刪除存在的元素E後:" + iter.next());
		}
	}
}
// 有序的
public class TreeSetTest {
	
	public static void main(String[] args) {
		TreeSet<String> tree = new TreeSet<String> ();
		tree.add("China");
		tree.add("America");
		tree.add("Japan");
		tree.add("Chinese");
		tree.add("Diio");
		Iterator<String> iter = tree.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());
		}
	}
}
/**
 * 測試TreeSet存儲自定義對象,並對對象排序的兩種方式
 */
public class TreeSetStudentTest {

	public static void main(String[] args) {
		System.out.println("下面是元素實現Comparable接口=====");
		TreeSet<Student> ts = new TreeSet<Student>();
		ts.add(new Student("zhangsan01", 25));
		ts.add(new Student("zhangsan02", 21));
		ts.add(new Student("zhangsan03", 18));
		ts.add(new Student("zhangsan04", 26));
		ts.add(new Student("zhangsan04", 27));
		ts.add(new Student("zhangsan04", 27));
		ts.add(new Student("zhangsan05", 50));

		Iterator<Student> it = ts.iterator();
		while (it.hasNext()) {
			Student stu = (Student) it.next();
			System.out.println("姓名:" + stu.getName() + " 年齡:" + stu.getAge());
		}
		
		
		System.out.println("下面是用自定義比較器類來實現比較的=====");
		TreeSet<Student> tsc = new TreeSet<Student>(new MyCompare());
		tsc.add(new Student("zhangsan01", 25));
		tsc.add(new Student("zhangsan02", 21));
		tsc.add(new Student("zhangsan03", 18));
		tsc.add(new Student("zhangsan04", 26));
		tsc.add(new Student("zhangsan04", 27));
		tsc.add(new Student("zhangsan04", 27));
		tsc.add(new Student("zhangsan05", 50));
		
		Iterator<Student> itc = tsc.iterator();
		while (itc.hasNext()) {
			Student stu = (Student) itc.next();
			System.out.println("姓名:" + stu.getName() + " 年齡:" + stu.getAge());
		}

	}

}

class Student implements Comparable<Object> {
	private String name;
	private int age;

	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	/**
	 * 年齡和名稱都相等的時候
	 */
	@Override  
    public boolean equals(Object obj) {  
        if (this == obj)  
            return true;  
        if (obj == null)  
            return false;  
        if (getClass() != obj.getClass())  
            return false;  
        Student other = (Student) obj;  
        if (age != other.age)  
            return false;  
        if (name == null) {  
            if (other.name != null)  
                return false;  
        } else if (!name.equals(other.name))  
            return false;  
        return true;  
    }  
	
	@Override  
    public int hashCode() {
        final int prime = 31;  
        int result = 1;  
        result = prime * result + age;  
        result = prime * result + ((name == null) ? 0 : name.hashCode());  
        System.out.println("hashCode : "+ result);  
        return result;  
    }  

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int compareTo(Object obj) {
		if (!(obj instanceof Student))
			throw new RuntimeException("不是學生對象");

		// 先按照年齡,之後看名稱
		Student stu = (Student) obj;
		if (this.age > stu.age)
			return 1;
		if (this.age == stu.age)
			return this.name.compareTo(stu.name);
		return -1;
	}
}

// 自定義比較類
class MyCompare implements Comparator<Object>   {  
    public int compare(Object o1,Object o2) {  
        Student s1 = (Student) o1;  
        Student s2 = (Student) o2;  
        // 先按名稱,之後看年齡
        int num = s1.getName().compareTo(s2.getName());  
        if( num == 0 )  
			return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));  
        return num;  
    }  
}  

說明:
HashSet:
當向HashSet集合中存入一個元素時,HashSet會調用該對象的hashCode()方法來得到該對象的hashCode值,然後根據 hashCode值來決定該對象在HashSet中存儲位置,如果相等,那就不能插入,如果不等,纔會調用equals()方法,如果equals結果爲true,說明已經存在,就不能再插入,如果爲false,可以插入。
簡單的說,HashSet集合判斷兩個元素相等的標準是兩個對象通過equals方法比較相等,並且兩個對象的hashCode()方法返回值相等。
注意,如果要把一個對象放入HashSet中,重寫該對象對應類的equals方法,也應該重寫其hashCode()方法。其規則是如果兩個對象通過equals方法比較返回true時,其hashCode也應該相同。另外,對象中用作equals比較標準的屬性,都應該用來計算 hashCode的值。

TreeSet:
TreeSet是怎麼實現有序的,它是按什麼規則排序的?
TreeSet的底層實現是採用紅-黑樹的數據結構,採用這種結構可以從Set中獲取有序的序列,但是前提條件是:元素必須實現Comparable接口,該接口中只用一個方法,就是compareTo()方法。當往Set中插入一個新的元素的時候,首先會遍歷Set中已經存在的元素,並調用compareTo()方法,根據返回的結果,決定插入位置。進而也就保證了元素的順序。
TreeSet是SortedSet接口的唯一實現類,TreeSet可以確保集合元素處於排序狀態。TreeSet支持兩種排序方式,自然排序 和定製排序,其中自然排序爲默認的排序方式。向TreeSet中加入的應該是同一個類的對象。
TreeSet判斷兩個對象不相等的方式是兩個對象通過equals方法返回false,或者通過CompareTo方法比較沒有返回0
自然排序
自然排序使用要排序元素的CompareTo(Object obj)方法來比較元素之間大小關係,然後將元素按照升序排列。
Java提供了一個Comparable接口,該接口裏定義了一個compareTo(Object obj)方法,該方法返回一個整數值,實現了該接口的對象就可以比較大小。
obj1.compareTo(obj2)方法如果返回0,則說明被比較的兩個對象相等,如果返回一個正數,則表明obj1大於obj2,如果是 負數,則表明obj1小於obj2。
如果我們將兩個對象的equals方法總是返回true,則這兩個對象的compareTo方法返回應該返回0
定製排序
自然排序是根據集合元素的大小,以升序排列,如果要定製排序,應該使用Comparator接口,實現 int compare(T o1,T o2)方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章