The Java interface set has many implementation classes, while HashSet and TreeSet are the two most commonly used, summarizing the 2 ways in which TreeSet can be sorted:
1. The TreeSet(comparator<. Super e> Comparator) Construction method specifies the TreeSet comparer to sort;
2. Using the TreeSet () construction method, and sorting the comparable interface for the elements that need to be added to the set set;
1. The TreeSet(comparator<. Super e> Comparator) Construction method specifies the TreeSet comparer to sort;
(1). Construct a Java bean loaded into TreeSet
For example:
Package src;
public class Foo {
private int num;
public int Getnum () {return
num;
}
public void setnum (int num) {
this.num = num;
}
Public String toString ()
{return
"foo:" + this.getnum () + ",";
}
}
(2). Implement the Comparator yourself
For example:
Package src;
Import Java.util.Comparator;
public class Mycomparator implements comparator<foo> {public
int compare (Foo f1,foo f2) {
if (F1.getnum () & Gt F2.getnum ())
{return
1;
}
else if (f1.getnum () = = F2.getnum ())
{return
0;
}
else
{
return-1;
}
}
}
(3) Specify comparer when new TreeSet
treeset<foo> set = new TreeSet (new Mycomparator ());
This way, the Set.add () element is sorted according to its own definition comparer.
2. Using the TreeSet () construction method, and sorting the comparable interface for the elements that need to be added to the set set;
This method does not require you to write a comparer, you need to implement the comparable interface to the elements in the set set, and the TreeSet collection is sorted according to the Bean's natural order
(1). Constructs the bean, needs to implement the comparable interface, and overrides the CompareTo () method, which defines the sort in the CompareTo method
For example:
Package src;
public class Foo implements comparable{
private int num;
public int Getnum () {return
num;
}
public void setnum (int num) {
this.num = num;
}
Public String toString ()
{return
"foo:" + this.getnum () + ",";
}
public int compareTo (Object obj) {
if (obj instanceof foo)
{
foo foo = (foo) obj;
if (This.num > Foo.getnum ())
{return
1;
}
else if (This.num = = Foo.getnum ())
{return
0;
}
else
{
return-1;
}
}
return 0;
}
}
(2). Use the constructed TreeSet () method directly when creating TreeSet
treeset<foo> set = new TreeSet ();
You do not need to specify a comparer so that when the Set.add () method is executed, the set collection is automatically sorted according to the way specified by the CompareTo () method in the bean.
Summary: 2 ways to choose one can achieve the goal.