Java enums in JDK 1.4

Constantly, we need to define enums. In Java 1.5, there is also a keyword. However, in JDK 1.4, we are out of the luck and have to come up something to simulate enums.

The motivation for enums is to avoid hardcoding same constants everywhere because it makes maintanence a nightmare, hard to track where the same constants are used, whether the upper/lower cases mean the same, the change of any constant requires changes in multiple places.

A simple way to create enums is using the infamous "public static final int". However, the general type without restriction(like int type) makes the interface signature(and consequently IDE prompts) quite confusing and error prone(pass in invalid data). So a better solution is proposed in "Effective Java" #21. Though we are strong typed, this approach creates a new problem - == is broken because we can't maintain the singletons in the vast different environments.

The reasons are:

1. there are clusters, acrossing several JVMs.
2. cross wires to a different JVM
3. different classloaders(so overriding readResolve() doesn't work either).

The compromise is to use equals().

To make matters worse, if there is a data structure among these constants, e.g., a tree structure, meaning, the constants are not quite mutual exclusive, then we need to maintain the structure as well. A typical case is the object class types in a class hierachy. For example, suppose we have a top class Automobile, and subclasses Car, Truck, Utility/Sports, and each of these has subclasses corresponding to manufactures/brand, BMW, BENZ, Toyota, etc. Then for each manufacture, they have different models. So we could keep going and eventually get a class hierarchy.

Now for some reason(many reasons, like performance, grouping, and others), we need to map this class hierarchy to an enum hierarchy and use it. A typical naive approach is using switch or if-else, a better approach is to build a visitor around it with double dispatch. However, building a fast visitor on top of non-exclusive enum hierarchy is not as trivial as we thought.
Another twist is documented in Hardcore Java chapter 7, when we have an enum is one class, and have another enum in its subclasses. So the challenge now becomes how to build an universal enum structure that could spread in several classes and is non-exclusive, while keep out the if-else checks.


References:

Hardcore Java, chapter 7
Javaworld java tip 122
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值