4

I've following scala code to convert (short, int, long, float, double,bigint) to byte array.

def getByteArray(value: Any, of_type: String) = {
    of_type match {
      case "short" => ByteBuffer.allocate(2).putShort(value.asInstanceOf[Short]).array()
      case "int" => ByteBuffer.allocate(4).putInt(value.asInstanceOf[Int]).array()
      case "long" => ByteBuffer.allocate(8).putLong(value.asInstanceOf[Long]).array()
      case "float" => ByteBuffer.allocate(4).putFloat(value.asInstanceOf[Float]).array()
      case "double" => ByteBuffer.allocate(8).putDouble(value.asInstanceOf[Double]).array()
      case "bigint" => BigInt(value.toString).toByteArray
    }
  }
  1. Is this all is needed ? Do I need to call any cleanup methods at the end such clear(), mark(), reset() to ensure there are no ByteBuffer leaks

  2. When I use allocateDirect methods, it throws below exception. So, does it mean allocateDirect method has no backing array ?

Exception in thread "main" java.lang.UnsupportedOperationException at java.nio.ByteBuffer.array(ByteBuffer.java:994)

mnille
  • 1,328
  • 4
  • 16
  • 20
codehammer
  • 876
  • 2
  • 10
  • 27

1 Answers1

2
  1. Yes, that is all that's needed. There is no cleanup to be done on nio Buffers.
  2. Indeed, direct buffers do not have a backing array.
sjrd
  • 21,805
  • 2
  • 61
  • 91