[英]Java List generics syntax for primitive types
I want to make a growable array of bytes. 我想制作一个可增长的字节数组。 Ie a list.
即列表。 In c# would usally do the following syntax
在c#中,通常会使用以下语法
List<byte> mylist = new List<byte>();
where as in java this syntax does not work and I have googled around and found the below code 在java中,这种语法不起作用,我已经google了,找到了下面的代码
List myList = new ArrayList();
but that is not what I want. 但这不是我想要的。 Any idea's where I am going wrong?
我知道哪里出错了?
您还可以使用GNU Trove库中的 TByteArrayList 。
Use the wrapper class Byte
: 使用包装类
Byte
:
List<Byte> mylist = new ArrayList<Byte>();
Then, because of autoboxing, you can still have: 然后,由于自动装箱,您仍然可以:
for (byte b : mylist) {
}
You have a Byte
class provided by the JRE. 您有JRE提供的
Byte
类。
This class is the corresponding class for the byte
primitive type. 该类是
byte
基元类型的对应类。
See here for primitive types. 请参阅此处了解原始类型。
You can do this : 你可以这样做 :
List<Byte> myList = new ArrayList<Byte>();
byte b = 127;
myList.add(b);
b = 0; // resetting
b = myList.get(0); // => b = 127 again
As Michael pointed in the comments : 正如迈克尔在评论中指出的:
List<Byte> myList = new ArrayList<Byte>();
Byte b = null;
myList.add(b);
byte primitiveByte = myList.get(0);
results in : 结果是 :
Exception in thread "main" java.lang.NullPointerException
at TestPrimitive.main(TestPrimitive.java:12)
Note that using an ArrayList<Byte>
to store a growable array of bytes is probably not a good idea, since each byte gets boxed, which means a new Byte object is allocated. 请注意,使用
ArrayList<Byte>
来存储可增长的字节数组可能不是一个好主意,因为每个字节都被装箱,这意味着分配了一个新的Byte对象。 So the total memory cost per byte is one pointer in the ArrayList + one Byte object. 因此,每个字节的总内存开销是ArrayList +一个Byte对象中的一个指针。
It's probably better to use a java.io.ByteArrayOutputStream
. 使用
java.io.ByteArrayOutputStream
可能更好。 There, the memory cost per byte is 1 byte. 在那里,每字节的存储器成本是1字节。
We can provide better advice if you describe the context a little more. 如果您更多地描述上下文,我们可以提供更好的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.