Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros and cons of a TreeSet [closed]

Just wondering what the pros and cons of a TreeSet is, if anyone could tell me please? Thanks!

like image 289
Rifk Avatar asked Aug 19 '09 06:08

Rifk


People also ask

What is the advantage of TreeSet?

Advantages of TreeSetAllows unique elements. Provides faster access and retrieval of elements. Stores elements in ascending order.

What is a benefit of using a TreeSet over a HashSet?

HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data.

Is TreeSet faster than HashSet?

Simply put, HashSet is faster than the TreeSet. HashSet provides constant-time performance for most operations like add(), remove() and contains(), versus the log(n) time offered by the TreeSet.

What advantages if any do Treesets have over Hashsets what advantages if any do Hashsets have over Treesets?

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.


1 Answers

One of the Collection classes. It lets you access the elements in your collection by key, or sequentially by key. It has considerably more overhead than ArrayList or HashMap. Use HashSet when you don’t need sequential access, just lookup by key. Use an ArrayList and use Arrays. sort if you just want the elements in order. TreeSet keeps the elements in order at all times. With ArrayList you just sort when you need to. With TreeSets the key must be embedded in the object you store in the collection. Often you might have TreeSet of Strings. All you can do then is tell if a given String is in the Set. It won’t find you an associated object he way a Treemap will. With a TreeMap the keys and the objects they are associated with are separate.

TreeSet and its brother TreeMap oddly have nothing to do with representing trees. Internally they use a tree organisation to give you an alphabetically sorted Set/Map, but you have no control over links between parents and children.

Internally TreeSet uses red-black trees. There is no need to presort the data to get a well-balanced tree. On the other hand, if the data are sorted (ascending or descending), it won’t hurt as it does with some other types of tree.

If you don’t supply a Comparator to define the ordering you want, TreeSet requires a Comparable implementation on the item class to define the natural order.

like image 135
RubyDubee Avatar answered Oct 11 '22 21:10

RubyDubee