1

I want to implement a method that converts a collection or a map into a byte array. So I wrote this snippet:

public static byte[] getByteArray(Collection<?> coll) {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;

    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(coll);
    } catch (IOException e) {
        e.printStackTrace;
    } finally {
        closeAll(baos, oos);
    }

    return baos.toByteArray();
 }

Then I discovered that Map doesn't extend Collection, hence I cannot have the same method. Do I really have to write another method with the same code, since they don't have interfaces in common? Like this:

public static byte[] getByteArray(Map<?, ?> map) {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;

    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(map);
    } catch (IOException e) {
        e.printStackTrace;
    } finally {
        closeAll(baos, oos);
    }

    return baos.toByteArray();
 }

Or maybe should I use another solution, e.g casting collections and maps to Object? Like this:

public static byte[] getByteArray(Collection<?> coll) {
    return getByteArray((Object) coll);
}

public static byte[] getByteArray(Map<?, ?> map) {
    return getByteArray((Object) map);
}

public static byte[] getByteArray(Object obj) {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;

    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
    } catch (IOException e) {
        e.printStackTrace;
    } finally {
        closeAll(baos, oos);
    }

    return baos.toByteArray();
 }

I believe the first solution is, obviously, a bad choice, and the latter is a bit strange.

Are there alternatives?

Community
  • 1
  • 1
gRizzlyGR
  • 306
  • 2
  • 9

1 Answers1

3

Just use your third code snippet, but without the first two methods; they are unnecessary.

ObjectOutputStream.writeObject takes an Object, and all you're really doing is wrapping that behavior with a resources cleanup. There's nothing inherently wrong with using Object for stuff; while it's usually not what you want to, sometimes it is, as in this case.

durron597
  • 31,968
  • 17
  • 99
  • 158