TreeSet and Hashset

package set_map_hashmap;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class Treeset_try {

public static void main(String[] args) {
	
	//https://www.cnblogs.com/xiaxj/p/7891963.html
	Set<Integer> test = new TreeSet<>();
	int a = 1;
	int b = 88;
	int c = 300;
	 
	test.add(a);
	test.add(b);
	test.add(c);
	 
	 //遍历集合test   利用foreach遍历          //输出结果:1   3   8    
	 for (Integer value : test) {
	     System.out.print(value+" ");
	 }    

	//利用Iterator实现遍历
	Iterator<Integer> value = test.iterator();
	while (value.hasNext()) {
	    int s = value.next();
	    System.out.print(s+" ");
	}                                //输出结果:1   3   8    
	
	  System.out.print("\ncode:" +test.hashCode());
	
	Set hs = new HashSet();		
	hs.add("世界军事");		
	hs.add("兵器知识");		
	hs.add("舰船知识");		
	hs.add("汉和防务");		
	System.out.println(hs);		// [舰船知识, 世界军事, 兵器知识, 汉和防务]		
	Iterator it = hs.iterator();		
	while (it.hasNext()) 
	{			
		System.out.println(it.next());		
	}

	
	System.out.println(hs.size()); // 4
	 
	// 如果此 set 尚未包含指定元素,则返回 true
	boolean add = hs.add("世界军事"); // false
	System.out.println(add);



	
	
	// Create a HashSet
	//https://beginnersbook.com/2014/08/difference-between-hashset-and-treeset/
	HashSet hset = new HashSet();

	//add elements to HashSet
	hset.add("Dteve");
	hset.add("Eatt");
	hset.add("Aovinda");
	hset.add("Fohn");
	hset.add("Zommy");

	// Displaying HashSet elements
	System.out.println("HashSet contains: "+ hset);

	// Creating a List of Treeset elements
	//HashSet gives better performance (faster) than TreeSet for the operations like add, 
	//remove, contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations.
	TreeSet list = new TreeSet(hset);

	// Displaying ArrayList elements
	System.out.println("TreeSet contains: "+ list);
	}

}

HashSet vs TreeSet

  1. HashSet gives better performance (faster) than TreeSet for the operations like add, remove, contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations.

  2. HashSet does not maintain any order of elements while TreeSet elements are sorted in ascending order by default.

Similarities:

  1. Both HashSet and TreeSet does not hold duplicate elements, which means both of these are duplicate free.

  2. If you want a sorted Set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it.

  3. Both of these classes are non-synchronized that means they are not thread-safe and should be synchronized explicitly when there is a need of thread-safe operations.

猜你喜欢

转载自blog.csdn.net/u013657997/article/details/82967664