The Comparable exception occurs when the TreeMap element is added.
Package com. swift; import java. util. comparator; import java. util. hashMap; import java. util. iterator; import java. util. map; import java. util. map. entry; import java. util. set; import java. util. treeMap; public class Map_keySet_entrySet {public static void main (String [] args) {/** the TreeMap set stores custom objects, and traverses and obtains */Map <Person, string> hm = new HashMap <Person, String> (); hm. put (new Person ("lisi", 18), "Canada"); h M. put (new Person ("zhangsa", 17), "Australia"); hm. put (new Person ("zhangsa", 17), "Australia"); hm. put (new Person ("wangwu", 20), "Singapore"); hm. put (new Person ("zhaoliu", 19), "new Zealand"); hm. put (new Person ("zhaoliu", 19), "new Zealand"); hm. put (new Person ("lisa", 22), "Dubai"); // if you cannot sort and compare data using TreeMap, a Comparable error occurs. In this case, you need to set the comparator Map <Person, string> tree = new TreeMap <Person, String> (new Comparator <Person> () {@ Override public int compare (Per Son arg0, Person arg1) {int num = arg0.getAge ()-arg1.getAge (); return num = 0? Arg0.getName (). compareTo (arg1.getName (): num ;}}); tree. put (new Person ("lisisi", 18), "china"); // keySet method 1 Set <Person> set = hm. keySet (); for (Person per: set) {System. out. println ("personnel:" + per. toString () + "from:" + hm. get (per);} Set <Person> set1 = tree. keySet (); for (Person per: set1) {System. out. println ("personnel:" + per. toString () + "from:" + tree. get (per);} // entrySet method 2 for (Map. entry <Person, String> en: hm. entrySet ()) {System. out. println (); System. out. println ("personnel:" + en. getKey (). toString () + "from:" + en. getValue ();} Map <Person, String> tree1 = new TreeMap <Person, String> (new Comparator <Person> () {@ Override public int compare (Person arg0, person arg1) {int num = arg0.getAge ()-arg1.getAge (); return num = 0? Arg0.getName (). compareTo (arg1.getName (): num ;}}); tree1.put (new Person ("fengqichanglin", 18), "langyabang"); System. out. println (); Iterator <?> It = tree1.entrySet (). iterator (); while (it. hasNext () {Entry <Person, String> entry = (Entry <Person, String>) it. next (); System. out. println (entry. getKey (). toString () + entry. getValue ());}}}