Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

TreeSet of enum not sorted

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This seems pretty basic but can't figure out why the enums appear to be unsorted in the second TreeSet. Am studying SCJP and don't feel real strong here so please give me some pointers. I can't override compareTo or equals and hashCode for that matter. This is not from any book. Mark

import java.util.*;

class TestCollect{

enum Children{
Michelle,
Lisa,
Sarina,
Brenda;
}

public static void main(String [] argv){
Set <String> set= new TreeSet<String>();
set.add(Children.Michelle.toString());
set.add(Children.Lisa.toString());
set.add(Children.Sarina.toString());
set.add(Children.Brenda.toString());
for (String i:set)
System.out.println(""+i);

Set <Children> set2= new TreeSet<Children>();
set2.add(Children.Michelle);
set2.add(Children.Lisa);
set2.add(Children.Sarina);
set2.add(Children.Brenda);
for (Children i:set2)
System.out.println(i.name());
}
}
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Note that Enum<E> implements Comparable<E>, and the compareTo method is final so you can't override it.

The output of the program implies that the natural ordering of an enum type is the order in which you declare the constants.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Adding to Keith's post: the API for Enum's compareTo() method states explicitly the same thing the output implies. If you want a different ordering (alphabetical perhaps?), you need to create a Comparator and use one of the TreeSet constructors which accepts a Comparator.
 
Mark Lund
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks guys. You've been very helpful! Mark
reply
    Bookmark Topic Watch Topic
  • New Topic