Java record -60-treeset thrown classcastexception

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.