susan susan - 4 months ago 7
Java Question

how to represent a destination list in a bytebuffer

A simple question:

I have a destination list, for example, A, B, C, D, E, ... and I need to put this destiantion list to a bytebuffer and send to a client using a java socket. At the client side, it will parse the bytebuffer and get the destination list.

I find two ways to do this: firstly, using format of dest_list_size + dest_list. Then the above example will becomes: 5+A;B;C;D;E; secondly, using a hashset to hold the destination list. Then how to transform hashset to a byte arrays and translates to a hashset?

I want to verify which way is better to go? Thanks.


Depending on the type of you destination field.

ByteBuffer bb = ...
Set<Character> destinations = new LinkedHashSet<Character>(
        Arrays.asList('A',  'B',  'C',  'D',  'E'));
bb.put((byte) destinations.size());
for (char b : destinations) bb.put((byte) b);


int size = bb.get();
Set<Character> destinations2 = new LinkedHashSet<Character>();
for (int i = 0; i < size; i++)
    destinations2.add((char) bb.get());


[A, B, C, D, E]

If you have a different type of destination or more than 127 destinations possible you need to change how you write that field/value as required.