我需要将我的Integer值转换为字节数组。为了不在每次调用我的intToBytes方法时重复创建ByteBuffer,我定义了一个静态ByteBuffer。将int转换为字节数组BufferOverflowException
private static ByteBuffer intBuffer = ByteBuffer.allocate(Integer.SIZE/Byte.SIZE);
public static byte[] intToBytes(int Value)
{
intBuffer.order(ByteOrder.LITTLE_ENDIAN);
intBuffer.putInt(Value);
return intBuffer.array();
}
我得到BufferOverflowException当我运行intToBytes方法。
W/System.err的:java.nio.BufferOverflowException W/System.err的:在java.nio.ByteArrayBuffer.putInt(ByteArrayBuffer.java:352) W/System.err的:在android.mobile.historian .Data.Convert.intToBytes(Convert.java:136)
在调试模式下,我看到intBuffer的容量是4,正如我对Integer值所期待的那样。那么这里有什么问题?
闻起来像我过早的优化。你是否证明这个对象的重新创建是你的应用程序的瓶颈?如果没有,不要担心它... – 2014-12-02 12:44:15