Skip to content

Commit

Permalink
Move the EnumOrdinal.md doc to the right place (it got overwritten by…
Browse files Browse the repository at this point in the history
… automation).

Also, add a comment about manually providing an index if you need a stable one.

PiperOrigin-RevId: 609531242
  • Loading branch information
graememorgan authored and Error Prone Team committed Feb 23, 2024
1 parent f768b0b commit f3dbb09
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions docs/bugpattern/EnumOrdinal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
You should almost never invoke the `Enum.ordinal()` method. The ordinal exists
only to support low-level utilities like `EnumSet`. The ordinal of a given enum
value is not guaranteed to be stable across builds because of the potential for
enum values to be added, removed, or reordered.

Prefer using enum value directly:

```java
ImmutableMap<MyEnum, String> MAPPING =
ImmutableMap.<MyEnum, String>builder()
.put(MyEnum.FOO, "Foo")
.put(MyEnum.BAR, "Bar");
```

to this:

```java
ImmutableMap<Integer, String> MAPPING =
ImmutableMap.<MyEnum, String>builder()
.put(MyEnum.FOO.ordinal(), "Foo")
.put(MyEnum.BAR.ordinal(), "Bar");
```

Or if you need a stable number for serialisation, consider defining an explicit
field on the enum instead:

```java
enum MyStableEnum {
FOO(1),
BAR(2),
;

private final int index;
MyStableEnum(int index) {
this.index = index;
}
}
```

0 comments on commit f3dbb09

Please sign in to comment.