Java Enum definition

java enum with values
java enum with string values
java enum constructor
java enum valueof
java enum key value
enum java 8
java enum int value
enum with multiple values in java

I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum:

class Enum<E extends Enum<E>>

Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a similar type parameter could be used.

It means that the type argument for enum has to derive from an enum which itself has the same type argument. How can this happen? By making the type argument the new type itself. So if I've got an enum called StatusCode, it would be equivalent to:

public class StatusCode extends Enum<StatusCode>

Now if you check the constraints, we've got Enum<StatusCode> - so E=StatusCode. Let's check: does E extend Enum<StatusCode>? Yes! We're okay.

You may well be asking yourself what the point of this is :) Well, it means that the API for Enum can refer to itself - for instance, being able to say that Enum<E> implements Comparable<E>. The base class is able to do the comparisons (in the case of enums) but it can make sure that it only compares the right kind of enums with each other. (EDIT: Well, nearly - see the edit at the bottom.)

I've used something similar in my C# port of ProtocolBuffers. There are "messages" (immutable) and "builders" (mutable, used to build a message) - and they come as pairs of types. The interfaces involved are:

public interface IBuilder<TMessage, TBuilder>
  where TMessage : IMessage<TMessage, TBuilder> 
  where TBuilder : IBuilder<TMessage, TBuilder>

public interface IMessage<TMessage, TBuilder>
  where TMessage : IMessage<TMessage, TBuilder> 
  where TBuilder : IBuilder<TMessage, TBuilder>

This means that from a message you can get an appropriate builder (e.g. to take a copy of a message and change some bits) and from a builder you can get an appropriate message when you've finished building it. It's a good job users of the API don't need to actually care about this though - it's horrendously complicated, and took several iterations to get to where it is.

EDIT: Note that this doesn't stop you from creating odd types which use a type argument which itself is okay, but which isn't the same type. The purpose is to give benefits in the right case rather than protect you from the wrong case.

So if Enum weren't handled "specially" in Java anyway, you could (as noted in comments) create the following types:

public class First extends Enum<First> {}
public class Second extends Enum<First> {}

Second would implement Comparable<First> rather than Comparable<Second>... but First itself would be fine.

Enum Types (The Java™ Tutorials > Learning the Java Language , An enum type is a special data type that enables for a variable to be a set of In the Java programming language, you define an enum type by using the enum  Java Enums. An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters:

The following is a modified version of the explanation from the book Java Generics and Collections: We have an Enum declared

enum Season { WINTER, SPRING, SUMMER, FALL }

which will be expanded to a class

final class Season extends ...

where ... is to be the somehow-parameterised base class for Enums. Let's work out what that has to be. Well, one of the requirements for Season is that it should implement Comparable<Season>. So we're going to need

Season extends ... implements Comparable<Season>

What could you use for ... that would allow this to work? Given that it has to be a parameterisation of Enum, the only choice is Enum<Season>, so that you can have:

Season extends Enum<Season>
Enum<Season> implements Comparable<Season>

So Enum is parameterised on types like Season. Abstract from Season and you get that the parameter of Enum is any type that satisfies

 E extends Enum<E>

Maurice Naftalin (co-author, Java Generics and Collections)

Java Enums, In Java (from 1.5), enums are represented using enum data type. The main objective of enum is to define our own data types(Enumerated Data Types). The Enum in Java is a data type which contains a fixed set of constants. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY), directions (NORTH, SOUTH, EAST, and WEST), season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.

This can be illustrated by a simple example and a technique which can be used to implement chained method calls for sub-classes. In an example below setName returns a Node so chaining won't work for the City:

class Node {
    String name;

    Node setName(String name) {
        this.name = name;
        return this;
    }
}

class City extends Node {
    int square;

    City setSquare(int square) {
        this.square = square;
        return this;
    }
}

public static void main(String[] args) {
    City city = new City()
        .setName("LA")
        .setSquare(100);    // won't compile, setName() returns Node
}

So we could reference a sub-class in a generic declaration, so that the City now returns the correct type:

abstract class Node<SELF extends Node<SELF>>{
    String name;

    SELF setName(String name) {
        this.name = name;
        return self();
    }

    protected abstract SELF self();
}

class City extends Node<City> {
    int square;

    City setSquare(int square) {
        this.square = square;
        return self();
    }

    @Override
    protected City self() {
        return this;
    }

    public static void main(String[] args) {
       City city = new City()
            .setName("LA")
            .setSquare(100);                 // ok!
    }
}

enum in Java, of constants. In this tutorial we will learn how to use enums in Java and. By Chaitanya Singh | Filed Under: Java Tutorials This is how we define Enum. A Java Enum is a special Java type used to define collections of constants. More precisely, a Java enum type is a special kind of Java class. An enum can contain constants, methods etc. Java enums were added in Java 5. This Java enum tutorial explains how to create and use a Java enum.

You are not the only one wondering what that means; see Chaotic Java blog.

"If a class extends this class, it should pass a parameter E. The parameter E’s bounds are for a class which extends this class with the same parameter E".

Java Enum Tutorial with examples, You can define constructors, methods, and fields inside enum types that make it very powerful. Let's extend the example above and implement  Java enum is a data type that allows you to define a set of related constants. java . lang . Enum is a base class for all Java enumeration types, but it’s not necessary to use it directly, you could define enum using enum keyword.

This post has totally clarified to me these problem of 'recursive generic types'. I just wanted to add another case where this particular structure is necessary.

Suppose you have generic nodes in a generic graph:

public abstract class Node<T extends Node<T>>
{
    public void addNeighbor(T);

    public void addNeighbors(Collection<? extends T> nodes);

    public Collection<T> getNeighbor();
}

Then you can have graphs of specialized types:

public class City extends Node<City>
{
    public void addNeighbor(City){...}

    public void addNeighbors(Collection<? extends City> nodes){...}

    public Collection<City> getNeighbor(){...}
}

A Guide to Java Enums, In Java, you use the enum type (short for enumeration), a special datatype introduced in Java The code to define an enum independently is:. enum in Java Enumerations serve the purpose of representing a group of named constants in a programming language. For example the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit.

Using Java Enums, In this tutorial, we will learn about enums in Java. We will learn The name() method returns the defined name of an enum constant in string form. The returned  The Java language specifically prohibits users from manually subclassing Enum, and all compiler-generated enums have the type parameter be the same as the type itself anyway, so the standard library implementation can rely on this to perform an unsafe cast. – newacct Feb 25 '15 at 6:09 |

Java enum & enum Class, How to Define and Use an Enumeration. An enumeration can be defined simply by creating a list of enum variable. Let us take an example for list of Subject  The enum keyword was introduced in Java 5. It denotes a special type of class that always extends the java.lang.Enum class. For the official documentation on their usage have a look at the documentation.

Java Enumerations, Enums are used to create our own data type like classes. The enum data type (​also known as Enumerated Data Type) is used to define an enum in Java. "What is enum in java " simple answer enum is a keyword in java and on more detail term java enum is type like class and interface and can be used to define a set of enum constants. Enum constants are implicitly static and final and you can not change there value once created.

Comments
  • Here's the explanation I like best: Groking Enum (aka Enum&lt;E extends Enum&lt;E>>)
  • This question has better answers: stackoverflow.com/a/3068001/2413303
  • have a look at sitepoint.com/self-types-with-javas-generics
  • I am really interested in the usefulness of this kind of thing versus the complexity. When I C#'ify your english description I get this: <pre> interface IBuilder<TMessage> { IMessage<TMessage> GetMessage(); } interface IMessage<TMessage> { IBuilder<TMessage> GetBuilder(); } </pre>
  • @artsrc: I can't remember offhand why it needs to be generic in both the builder and the message. I'm pretty sure I wouldn't have gone down that route if I hadn't needed it though :)
  • @JonSkeet: I might be too late, but couldn't stop asking. Does the <E extends Enum<E>> really stops me to pass a type argument which is not the new type being defined? I mean, for example, I could define two subtypes - one is public class First extends Enum<First>, and the other one is public class Second extends Enum<First>. The declaration isn't stopping me to mix subtypes here.
  • @SayemAhmed: Yes, it doesn't prevent that aspect of mixing up the types. I'll add a note about this.
  • "The purpose is to give benefits in the right case rather than protect you from the wrong case." But in the case of Enum there are no benefits beyond the benefits that would be given by just class Enum<E>.
  • @newacct OK, I get it now: you'd like all enums to be instances of Enum<E>, right? (Because if they are instances of an Enum subtype, the argument above applies.) But then you won't have type-safe enums any more, so losing the point of having enums at all.
  • @newacct Don't you want to insist that Season implements Comparable<Season>?
  • Well, if Season is created via an enum declaration, the compiler already makes it extend Enum<Season>. There is no point to "insist". If you define your own class that extends Enum, then it's already possible to make Foo extend Enum<Season>.