Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!

like image 828
Chap Avatar asked Sep 19 '25 15:09

Chap


2 Answers

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).

like image 91
Mark Peters Avatar answered Sep 21 '25 05:09

Mark Peters


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.

like image 31
Peter Lawrey Avatar answered Sep 21 '25 05:09

Peter Lawrey