Tree:
A tree is a non linear data structure which is used to represent the data according to some relation.
Binary tree:
It is a type of tree where parent node can have maximum of two child nodes only.
TreeSet Properties:
✓ It uses binary tree as the underlying data structure
✓ The elements of the TreeSet will be sorted by the TreeSet in two ways.
1. Using default natural sorting order
2. Using customised sorting order
✓ TreeSet uses compareTo() of Comparable interface to sort the given object.
✓ To sort the elements according to customized sorting order or default sorting order, we use comparator sorting interface.
ex:
public class TressSet {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(50);
ts.add(30);
ts.add(10);
ts.add(40);
ts.add(20);
for(Object ob : ts) {
System.out.println(ob);
}
}
}
Output:
10
20
30
40
50
1. Comparable interface:
✓ Comparable interface is used to sort the object according to default natural sorting order.
✓ This interface contains only one abstract method by the name compareTo().
✓ We should override compareTo() to specify the default sorting order for the user defined classes.
✓compareTo() returns,
1. Zero(0) :
If given object value is equal to another object value, returns zero.
2. +ve number :
If given object value is greater than another object value, returns positive number.
3. -ve number :
If given object value is lesser than another object value, returns negetive number.