Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics using Enum in Java

I have an enum

public enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY 

}

I want to make a class which can take values of type Days. So I used Java Generics

public class State<T extend Days>

But there is an error

The type parameter T should not be bounded by the final type Days. 
Final types cannot be further extended

How can I resolve this?

like image 777
Rog Matthews Avatar asked Feb 13 '12 08:02

Rog Matthews


People also ask

Can enum be used for generics Java?

Java enums will be enhanced with generics support and with the ability to add methods to individual items, a new JEP shows. Since both features can be delivered with the same code change, they are bundled together in the same JEP. The change only affects the Java compiler, and therefore no runtime changes are needed.

Is enum allowed in switch case?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.

What is Java generics with examples?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

Can we use enum in switch case Java?

Java allows us to use enum in switch statement. Java enum is a class that represent the group of constants.


2 Answers

enums are final types, which means, you can not extend from them

a generic like wants a Class as Parameter which is Days or an extended class, but the extended class is not possible

so the only parameter possible is Days and you don't need a generic, if only one value is possible

like image 128
Hachi Avatar answered Sep 20 '22 03:09

Hachi


Don't use a generics bound. There's no need. Just use an unbounded type, like this:

public class State<T> {
    public State(T startState) {
        // whatever
    } 
}

And to use it:

State<Days> dayState = new State<Days>(Days.SUNDAY);

This is a straightforward typed class that doesn't need a bound.

The only bound that might make sense is a bound to an enum:

public class State<T extends Enum<T>> {
    public State(T startState) {
        // whatever
    } 
} 

This version requires that the generic parameter be an enum. With this version the above usage example would still compile, but this would not compile (for example):

State<String> dayState = new State<String>("hello");

because String is not an enum.

like image 29
Bohemian Avatar answered Sep 20 '22 03:09

Bohemian