{{announcement.body}}
{{announcement.title}}

# Java Holiday Calendar 2016 (Day 22): Use Enums as Method Parameters

DZone 's Guide to

# Java Holiday Calendar 2016 (Day 22): Use Enums as Method Parameters

### Using Enums as parameters can greatly enhance the versatility of your methods. This example shows off how Enums can be used to nimbly and simply sort your lists.

· Java Zone ·
Free Resource

Comment (3)

Save
{{ articles[0].views | formatCount}} Views

Today's tip is about using Enums as parameters to indicate method behavior. Let us here the fairy tail of Prince Sort and it will be more apparent why this can be a good thing.

Once upon a time there was a Prince with a sort method like this:

``void sort(); // 1``

Everything was good until the Prince realized he needed to sort in either direction. And so, he went about and added a boolean like this:

``void sort(boolean descending); // 2``

Everything was good until the Prince wanted to indicate that sorting could be done in arbitrary order. And so, he went about and changed the boolean to Boolean:

``void sort(Boolean descending); // 3, null means any order``

Everything was good until the Prince wanted to indicate that sorting could be done in random order too. And so, he went about and changed the Boolean to an int:

``void sort(int flag); // 4, 0 = asc, 1 = desc, 2 = unspec, 3 = random``

Now, the most beautiful Princess appeared out of thin air and she wore a wonderful dress and she held the most prominent PhD in computer science. The Princess told the Prince "thou shalt introduce Enums in thy methods." Here is my humble gift to you:

``````enum Order {
ASC, DESC, UNSPECIFIED, RANDOM;
}``````

So, he went about and changed the int to the Order Enum like this:

``void sort(Order order);``

The Prince was delighted and promised that from now on, he would introduce Enums in step 2 and they both lived happily ever after!

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Topics:
java ,enums ,method parameter ,sorting ,tutorial

Comment (3)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.