字节数组中的整数列表 [英] List of Integers into byte array
问题描述
我有一个 LinkedList<具有大号(3912984或更大)的整数> ,我想将这些元素复制到字节数组中.整数是0或1,所以我不需要更改数组的大小,我只想一个一个地复制元素,确切地说就是它们.当然,我知道最简单的方法是:
I have a LinkedList < Integer > with big size (3912984 or more) and I wanna copy these elements in a byte array. The integers are 0 or 1, so I don't need any change of size for array, I want just to copy elements one by one, exactly how they are. Of course, I know the simplest way is :
for(int i = 0; i < list.size(); i++)
array[i] = (byte)(int) list.get(i);
但是这种方法太慢了,我的程序在几个小时之前还没有结束!您是否可以知道另一种方式(更快,如.NET的Buffer.BlockCopy()之类的),或者我必须更改数据结构?
But this method is too slow and my program doesn't end before hours ! Can you know another way (faster, something like Buffer.BlockCopy() of .NET) or I have to change data structures?
推荐答案
Number类中提供了byteValue()方法.数字以整数,双精度,浮点数等扩展.
There is byteValue() method available in Number class. Number is extended by Integer, Double, Float etc.
List<Integer> list = getNumbers();
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext())
{
Integer i = iterator.next()
byteArray[index] = i.byteValue();
}
您也可以使用java.nio.MappedByteBuffer
类进行块复制.参见 http://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.html .
You can also use java.nio.MappedByteBuffer
class for block copy. see http://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.html.
MappedByteBuffer等效于.NET中的Buffer.BlockCopy()
MappedByteBuffer is equivalent to Buffer.BlockCopy() in .NET
这篇关于字节数组中的整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!