Re: Why Generics?
- From: Phillip Lord <p.lord@xxxxxxxxxxxx>
- Date: 25 May 2005 15:20:00 +0100
>>>>> "Chris" == Chris Uppal <chris.uppal@xxxxxxxxxxxxxxxxxxxxxxxxxxx> writes:
Chris> Dale King wrote:
>> [../] the new enumerations are (in my
>> > understanding) just a little syntactic sugar provided by the
>> > javac compiler. So clearly type safe enums were always
>> > possible.
>>
>> There is actually one part of enums that was not possible before
>> and that was the ability to use them as cases in a switch
>> statement.
Chris> It was always possible, the new enums don't generate code
Chris> that couldn't be expressed in "normal" Java. Supporting
Chris> switch would require a fairly unpleasant amount of wordy
Chris> duplication, though. You'd have to have a public static
Chris> final int field corresponding the the 'ordinal' of each enum
Chris> object, which is obviously error prone unless the compiler
Chris> does it for you.
I think, actually, you are wrong and it doesn't work. The problem is
that with switch case, the value of the cases must be a int or char
definable at compile time.
If you do
class Enum{
public static final int ord;
private static int number;
Enum()
{
ord = number++;
}
Enum a = new Enum();
Enum b = new Enum();
}
case a.ord
won't work, because we don't know the value of a.ord. Actually, we can
work this out but the compile wasn't clever enough.
Now under the hood, switch case is implemented as a hash (so it's
constant time to any case idependent of the number of cases). It uses
the knowledge of the case values to determine who this look up happens
(sparse or otherwise).
The syntactic sugar that switch/case is translated into cascading
if/then/else statements.
So the OP was correct. You couldn't use switch/case. In a sense, you
still can't, as you do not get the constant time access when
switch/case is used with a enum, that you do otherwise.
Chris> OTOH, if you use your own implementation of the type-safe
Chris> enum pattern, then their object-nature is not hidden by the
Chris> compiler and so you can use polymorphism to avoid having to
Chris> use switch statements in the first place.
Which is how I generally did it, although you are moving from a Enum
pattern toward a Command pattern I think.
Phil
.
- Follow-Ups:
- Re: Why Generics?
- From: Chris Uppal
- Re: Why Generics?
- References:
- Why Generics?
- From: David Blickstein
- Re: Why Generics?
- From: Eric Sosman
- Re: Why Generics?
- From: Chris Uppal
- Re: Why Generics?
- From: Mike Schilling
- Re: Why Generics?
- From: Chris Uppal
- Re: Why Generics?
- From: David Blickstein
- Re: Why Generics?
- From: David Blickstein
- Re: Why Generics?
- From: Dale King
- Re: Why Generics?
- From: Chris Uppal
- Why Generics?
- Prev by Date: Re: peer to peer messaging
- Next by Date: Re: Creating a unique random id
- Previous by thread: Re: Why Generics?
- Next by thread: Re: Why Generics?
- Index(es):
Relevant Pages
|