开发者

best way to model java object with multiple datatypes

What is the most memory efficient way to model a java object that will have multiple possible datatypes: For example

public class Cell{

   short type

   int _int
   double _double
   String _string
}

Then instantiate this object and when setting the type set the appropriate value while leaving all others null. (I suspect this will take memory even if null except for String?)

Or,

public class Cell
{

   short type
}
public class StringCell extends Cell
{
   String _string

}

Where each type is a subclass of some common class that has only the appropriate 开发者_运维知识库datatype. (I suspect there will be some memory over head associated with subclasses)


This looks like a classic problem for generics since you say "setting the type set the appropriate value while leaving all others null."

public class Cell<T> {
    T value;
}

Then you can have...

Cell<String>  stringCell   = ...
Cell<Integer> integerCell  = ...

If Cell implemented a good interface you could even have a well defined collection of heterogeneous typed Cells.


You are over thinking this. If you really need this then stick to primitives and also look if Flyweight pattern can help.


If you need to work with int, long, float, and double primitives, the most efficient way IS to use the primitive themselves. However, setting them to null is impossible. Simply declaring them in the class will take up space.

Going with a subclass approach may work, but that begs the question, what value is the base class? I'd lean towards an Interface, with different implementations per primitive type. That way you have no inheritance overhead (though I doubt there is any) AND you only have the primitive you need.

I still question what you would put on that Interface though. Possibly some sort of a Render method?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜