Enum Ordinal And Values Array Indexing
Read an enum constant position with ordinal() and valueOf(), and see why declaration order, not source order of use, decides every ordinal value.
Code
import java.util.Arrays;
public class TierPositions {
enum Tier { BRONZE, SILVER, GOLD, PLATINUM }
public static void main(String[] args) {
// ordinal() 是声明顺序的下标:从 0 开始,与使用位置无关
for (Tier t : Tier.values()) {
System.out.println(t + " ordinal=" + t.ordinal());
}
// values() 数组按下标索引,等价于按 ordinal() 查找
Tier[] tiers = Tier.values();
System.out.println("index 2: " + tiers[2]);
// name/valueOf 互逆:valueOf(name) 还原常量,大小写必须精确一致
System.out.println("valueOf: " + Tier.valueOf("GOLD"));
try {
Tier.valueOf("gold");
} catch (IllegalArgumentException e) {
System.out.println("valueOf lowercase rejected: " + e.getClass().getSimpleName());
}
// 声明顺序一旦插入新常量,后续所有 ordinal 都会移动——别把它持久化
System.out.println("declared count: " + tiers.length);
System.out.println("array identity: " + Arrays.toString(tiers));
}
}A close pass over the snippet
Everything happens inside the classes TierPositions and Tier and the function main.
A single loop drives the file — for (Tier t : Tier.values()).
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The primary signature is public static void main(String[] args)
The output arrives labeled — index 2:, valueOf:, valueOf lowercase rejected: — when the file runs.
Key statements
Tier[] tiers = Tier.values();
Tier.valueOf("gold");
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Enum Ordinal And Values Array Indexing print when run?
- Run it as a complete program — the output lines carry labels such as `index 2:`, `valueOf:`, `valueOf lowercase rejected:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.