title: Byte-size enum in Java
body: <p>I have a class of which there may be many instances (on a mobile device), so I'm trying to minimize the size. One of my fields is a "DrawTarget" that indicates whether drawing operations are being ignored, queued to a path or drawn to the display. I would like it to take a single byte or less since there are only 3 possible values, but I would also like it to be friendly code so I don't have hard-coded numbers all over. One thought is to use an enum like:</p>
  
  <pre><code>public enum DrawTarget {
      Invisible,
      Path,
      Canvas
  }
  </code></pre>
  
  <p>But from what I read, a Java enum doesn't allow you to specify the memory layout -- I can't request that the enum values represent a byte-size value -- and I guess enum values end up being integer-sized values in Java.</p>
  
  <p>So I thought about maybe making an implicit conversion operator in the enum... is this possible in Java? Or is my best option to implement something like this within the enum:</p>
  
  <pre><code>public static DrawTarget fromValue(byte value) {
      switch (value) {
      case 0:
          return Invisible;
      case 1:
          return Path;
      default:
          return Canvas;
      }
  }
  </code></pre>
  
  <p>and then call DrawTarget.fromValue wherever I want to access the value?</p>
  
  <p>Or should I just create a single-byte class since apparently (from what I read in my research on this) enums are basically just special classes in Java anyway?</p>
  
  <pre><code>public class DrawTarget {
      public static final byte Invisible = 0;
      public static final byte Path = 1;
      public static final byte Canvas = 2;
  }
  </code></pre>
  
  <p>But how to I represent the value of an enum instance if I use that last solution? I still need a way to allow the "=" operator to accept one of the static fields of the class... like a conversion constructor or an assignment operator overload.</p>
  
  <p>I suspect, however, that any class object, being a reference type, will take more than a byte for each instance. Is that true?</p>