I need to add the user identified by his identifier to the set and at runtime, all user forms that should be sorted by this identifier.
I created a TreeSet, added some user objects and tried to iterate through it.
Here is my attempt:
//irrelevant code removed TreeSet<User> userSet = new TreeSet<User>(); userSet.add(new User(2)); userSet.add(new User(1)); userSet.add(new User(3)); Iterator<User> iterator = userSet.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); }
I wrote a User class, where one of the id and constructor fields has id as a parameter.
public class User { private int id;
When I run this code, I get a ClassCastException.
Here is the stack:
Exception in thread "main" java.lang.ClassCastException: OrderedUsers$User cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1188) at java.util.TreeMap.put(TreeMap.java:531) at java.util.TreeSet.add(TreeSet.java:255) at OrderedUsers.<init>(OrderedUsers.java:9) at Main.main(Main.java:6)
What am I doing wrong?
user3366594
source share