TreeSet implements the SortedSet also implements the set, but it is not a random object can be stored:
public class Treesettest {public static void main (string[] args) {TreeSet tree = new TreeSet (); Tree.add (New Pepole ("Zhangsan")); Tree.add (New Pepole ("Lisi")); System.out.println (tree); }}class pepole{int age; String name; Public pepole (String name) {this.name = name; }}
Executing the above code will get the following exception information:
Exception in thread "main" Java.lang.ClassCastException:my.set.Pepole cannot is cast to java.lang.Comparable at java.u Til. Treemap.put (treemap.java:542) at Java.util.TreeSet.add (treeset.java:238) at My.set.TreeSetTest.main ( TREESETTEST.JAVA:10)
The above exception appears in the TreeSet to put the second object times of the exception, put the first time there is no problem.
When the second object is placed, the second object is compared with the object in the TreeSet to see if it repeats, but our own definition of pepole does not specify a collation, so an exception is thrown.
See the Add method for TreeSet to find a hint:
ClassCastException
-If the specified object cannot be compared to the current element of this set
Java record -60-treeset thrown classcastexception