-
Notifications
You must be signed in to change notification settings - Fork 732
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
- Loading branch information
1 parent
f768b0b
commit f3dbb09
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
``` |