How can I store byte[]'s in a Vector in Java?
I'm reading a binary file开发者_开发问答 and storing each record into a byte[]. Now I'd like to collect these records into a Java Vector. (So that it can grow indefinitely.) But Vector takes Objects, not primitives (or arrays of primitives, as far as I can tell).
Is there way to "box" an array of primitives, or am I going to have to rewrite my code to turn my arrays into Arrays and my bytes into Bytes?
I tried concatenating the bytes into a String, but that failed miserable, due to String.append()'s propensity to treat my bytes as ints and convert them into String-y decimal representations!!
byte[]
is-an Object
(all arrays are, even primitive ones). There is nothing stopping you from adding a byte[]
to a Vector
.
Vector<byte[]> records = new Vector<byte[]>();
byte[] firstRecord = readRecord();
records.add(firstRecord);
Though it doesn't smell like a good design. Also, you should favour passing around List
(the interface) over passing around a Vector
(a concrete implementation of List
).
You can add all the bytes in a byte[] to a Vector<Byte> by looping through each byte.
However, I wouldn't suggest you use Vector as it is a legacy class which was replaced in Java 1.2 (1998)
You can use an ArrayList instead, but this will use 4-16 times as much memory as the original byte[].
If you cannot use TByteArrayList, I suggest you use ByteArrayOutputStream and ByteArrayInputStream.
If you absolutely cannot convert the byte's into Bytes, then you might look into a primitive collection library such as Colt. It was written for high performance scientific stuff but it has primitive collection types that you can use.
You can do:
byte[] byteArr = new byte[]{0x41, 0x43};
List<byte[]> listBytes = Arrays.asList(byteArr); // to get a list
List<byte[]> list = new Vector<byte[]>(listBytes); // to instantiate a vector
System.out.println(Arrays.toString(list.get(0)));
Update (Based on your comments)
List<byte[]> l = new Vector<byte[]>(); // to instantiate a vector
l.add(new byte[]{0x51, 0x52});
System.out.println(Arrays.toString(l.get(0)));
OUTPUT
[81, 82]
I catch what u mean, Yes it is impossible to put array of somethings into a Vector or even into ArrayList as one element, let me explain why the following code is completely right but we misunderstand it
Vector<byte[]> records = new Vector<byte[]>();
byte[] firstRecord = readRecord();
records.add(firstRecord);
The third line of this code doesn't put the array into the Vector but instead it puts the reference firstRecord into that Vector. Then if we change the contents of firstRecord after putting it in the vector, what happen is that we change the content of the Vector because we have two references to the same thing.
精彩评论