Skip to content

Commit f3dbb09

Browse files
graememorganError Prone Team
authored andcommitted
Move the EnumOrdinal.md doc to the right place (it got overwritten by automation).
Also, add a comment about manually providing an index if you need a stable one. PiperOrigin-RevId: 609531242
1 parent f768b0b commit f3dbb09

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/bugpattern/EnumOrdinal.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
You should almost never invoke the `Enum.ordinal()` method. The ordinal exists
2+
only to support low-level utilities like `EnumSet`. The ordinal of a given enum
3+
value is not guaranteed to be stable across builds because of the potential for
4+
enum values to be added, removed, or reordered.
5+
6+
Prefer using enum value directly:
7+
8+
```java
9+
ImmutableMap<MyEnum, String> MAPPING =
10+
ImmutableMap.<MyEnum, String>builder()
11+
.put(MyEnum.FOO, "Foo")
12+
.put(MyEnum.BAR, "Bar");
13+
```
14+
15+
to this:
16+
17+
```java
18+
ImmutableMap<Integer, String> MAPPING =
19+
ImmutableMap.<MyEnum, String>builder()
20+
.put(MyEnum.FOO.ordinal(), "Foo")
21+
.put(MyEnum.BAR.ordinal(), "Bar");
22+
```
23+
24+
Or if you need a stable number for serialisation, consider defining an explicit
25+
field on the enum instead:
26+
27+
```java
28+
enum MyStableEnum {
29+
FOO(1),
30+
BAR(2),
31+
;
32+
33+
private final int index;
34+
MyStableEnum(int index) {
35+
this.index = index;
36+
}
37+
}
38+
```

0 commit comments

Comments
 (0)