Generating a random enum in java

Here’s a code fragment for how to create a random enum in java from an Enum class object clazz (rnd is an object of type java.util.Random)


Object[] objs = EnumSet.allOf(clazz).toArray();
return objs[rnd.nextInt(objs.length)];

3 Responses to “Generating a random enum in java”

  1. tomp Says:

    Hello John,

    Great to see you using your site! I thought I would explain how to enter code fragments in the wordpress editor.

    in the editor there are two tabs “visual” & “code”. Here, “code” refers to the html code not java code snipits. Most bloggers write in code mode so they can easily enter html tags in thier post.

    java code in a post needs to be in inside tags. while on the “code” tab there are buttons for entering html tags in your post.

    so, write commentary normally then click the [code] button to enter an opening tag, write your java code, then click the [/code] button again to add a closing tag.

    right now I think just uses a monospace font. many blogs with code discussions will use css to format the code elements with indent and background color etc.

  2. tomp Says:

    hehe, it looks like wordpress stripped out my html tag examples in my previous comment. oh well, you’ll figure it out.

  3. admin Says:

    Thanks Tom! I modified the post. Looks a lot better. I suppose now I need to learn some CSS…..

Leave a Reply

You must be logged in to post a comment.