基本类型的 Java 列表泛型语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2302003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java List generics syntax for primitive types
提问by Ciarán
I want to make a growable array of bytes. I.e 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中这种语法不起作用,我在谷歌上搜索并找到了下面的代码
List myList = new ArrayList();
but that is not what I want. Any idea's where I am going wrong?
但这不是我想要的。知道我哪里出错了吗?
采纳答案by Bozho
Use the wrapper class Byte:
使用包装类Byte:
List<Byte> mylist = new ArrayList<Byte>();
Then, because of autoboxing, you can still have:
然后,由于自动装箱,您仍然可以:
for (byte b : mylist) {
}
回答by finnw
You could also use TByteArrayListfrom the GNU Trove library.
你也可以使用TByteArrayList从GNU特罗韦库。
回答by glmxndr
You have a Byteclass provided by the JRE.
您有一个ByteJRE 提供的类。
This class is the corresponding class for the byteprimitive type.
这个类是byte原始类型的对应类。
See herefor 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)
回答by glmxndr
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. So the total memory cost per byte is one pointer in the ArrayList + one Byte object.
请注意,使用ArrayList<Byte>来存储可增长的字节数组可能不是一个好主意,因为每个字节都被装箱,这意味着分配了一个新的 Byte 对象。所以每字节的总内存成本是 ArrayList 中的一个指针 + 一个 Byte 对象。
It's probably better to use a java.io.ByteArrayOutputStream. There, the memory cost per byte is 1 byte.
使用java.io.ByteArrayOutputStream. 在那里,每字节的内存成本是 1 个字节。
We can provide better advice if you describe the context a little more.
如果您多描述一下上下文,我们可以提供更好的建议。

