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?