OMG: Using a triple cast.

I have used double casts before but today found myself writing a triple cast. :P

The situation was; I need a method which returned the default value for a type.


public static <T> T nullValue(Class<T> clazz) {
if (clazz == byte.class)
return (T) (Byte) (byte) 0;
// other primitive types handled.
return null;
}


Certainly this is casting madness. So I wrote the method a different way.


static {
NULL_MAP.put(byte.class, (byte) 0);
// other primitive types handled.
}

public static <T> T nullValue(Class<T> clazz) {
return (T) NULL_MAP.get(clazz);
}


There the same casting is going on, but one cast is implied and the other two are seperated. Its not as ugly and more efficient. :)

Comments

  1. > (T) (Byte) (byte) 0;
    Wow, you like autoboxing.
    (T) Byte.valueOf((byte)0); would be nices. Still ugly though (-:
    But more important IMO is that this way each time you call nullValue you create new instances of primitive types wrappers, which of pointless because they're immutable anyway.

    IMO the best part about your Map approach is that you don't create new instances of Byte, Integer etc anymore, so this is much more efficient.

    ReplyDelete
  2. valueOf() does not create new instances, it uses a cache internally. Also, I think it would be more correct to use Byte.TYPE, but I may be wrong here :)

    ReplyDelete
  3. @Nacho is correct for whole number types, (and Boolean) however for float and double, there is no cache so @mvmn is correct for these.

    ReplyDelete

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

Low Latency Microservices, A Retrospective

Unusual Java: StackTrace Extends Throwable