Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a better way to find the size of the enum? [duplicate]

Tags:

java

oop

enums

Possible Duplicate:
Enum values().length vs private field

I want to know how which of these ways to find the size of the enum is better.

This way:

public enum Company {

    AUDI(4), BMW(5), CADILLAC(11), FORD(44), JAGUAR(45);

    private final int id;
    public final int length = Company.values().length;

    private Company(int id) {
        this.id = id;
    }
}

Or this way:

public enum Company {

    AUDI(4), BMW(5), CADILLAC(11), FORD(44), JAGUAR(45);

    private final int id;
    public final int length = 5;

    private Company(int id) {
        this.id = id;
    }
}
like image 355
amod Avatar asked Nov 16 '25 07:11

amod


2 Answers

given -

enum Widgets {TINY, SMALL, AVERAGE, BIG};

the size of Widgets is:

Widgets.values().length
like image 149
Shadow Avatar answered Nov 18 '25 23:11

Shadow


The first one, but make it static so you don't make multiple copies of the array.

public final static int length = Company.values().length;
like image 43
dogbane Avatar answered Nov 18 '25 22:11

dogbane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!