treeset

Treeset to order elements in descending order

让人想犯罪 __ 提交于 2019-11-27 02:31:05
问题 Here is the piece of code that I have used for Java 5.0 TreeSet<Integer> treeSetObj = new TreeSet<Integer>( Collections.reverseOrder() ) ; Collections.reverseOrder() is used to obtain a comparator in order to reverse the way the elements are stored and iterated. Is there a more optimized way of doing it? 回答1: Why do you think this approach won't be optimized? The reverse order Comparator is simply going to be flipping the sign of the output from the actual Comparator (or output from compareTo

Why does TreeSet throw a ClassCastException?

大憨熊 提交于 2019-11-27 01:44:54
I am trying to add two 'Employee' objects to a TreeSet: Set<Employee> s = new TreeSet<Employee>(); s.add(new Employee(1001)); s.add(new Employee(1002)); But it throws a ClassCastException: Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable at java.util.TreeMap.put(TreeMap.java:542) at java.util.TreeSet.add(TreeSet.java:238) at MyClient.main(MyClient.java:9) But if I add only one object to the TreeSet: Set<Employee> s = new TreeSet<Employee>(); s.add(new Employee(1001)); Or if I use a HashSet instead: Set<Employee> s = new HashSet<Employee>(

Why does TreeSet throw a ClassCastException?

佐手、 提交于 2019-11-26 09:45:34
问题 I am trying to add two \'Employee\' objects to a TreeSet: Set<Employee> s = new TreeSet<Employee>(); s.add(new Employee(1001)); s.add(new Employee(1002)); But it throws a ClassCastException: Exception in thread \"main\" java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable at java.util.TreeMap.put(TreeMap.java:542) at java.util.TreeSet.add(TreeSet.java:238) at MyClient.main(MyClient.java:9) But if I add only one object to the TreeSet: Set<Employee> s = new TreeSet

Hashset vs Treeset

喜夏-厌秋 提交于 2019-11-25 23:35:39
问题 I\'ve always loved trees, that nice O(n*log(n)) and the tidiness of them. However, every software engineer I\'ve ever known has asked me pointedly why I would use a TreeSet . From a CS background, I don\'t think it matters all that much which you use, and I don\'t care to mess around with hash functions and buckets (in the case of Java ). In which cases should I use a HashSet over a TreeSet ? 回答1: HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add,