在我们平时的程序开发过程中,当用到了byte[]之间的操作的时候我们最好是使用ByteBuffer,它为我们节省很多的空间,如下的实例,我需要把一个含有多个byte[]的类的属性都合并起来,此类如下所示:
public class MessageEntity {
public MessageEntity() {
super();
}
public MessageEntity(byte[] bodyTotalLengthDefine, byte[] commandId,
byte[] messageBody, byte[] reserve, byte[] sequenceId, byte[] uuid) {
super();
body_total_length_define = bodyTotalLengthDefine;
command_id = commandId;
message_body = messageBody;
this.reserve = reserve;
sequence_id = sequenceId;
this.uuid = uuid;
}
private byte[] body_total_length_define;
private byte[] command_id;
private byte[] message_body;
private byte[] reserve;
private byte[] sequence_id;
private byte[] uuid;
}
然后我现在要在一个方法中获取出这个类的一个实例的属性的byte[]的集合,这个时候我们可以有如下两种方式来实现此功能:
public static byte[] getMessageByte(MessageEntity message) {
byte[] body_total_length_define = message.getBody_total_length_define();
byte[] command_id= message.getCommand_id();
byte[] message_body= message.getMessage_body();
byte[] reserve= message.getReserve();
byte[] sequence_id= message.getSequence_id();
byte[] uuid= message.getUuid();
int message_length = body_total_length_define.length+command_id.length+
message_body.length+reserve.length+sequence_id.length+uuid.length;
byte[] messageByte = new byte[message_length];
System.arraycopy(body_total_length_define, 0, messageByte, 0, body_total_length_define.length);
System.arraycopy(command_id, 0, messageByte, body_total_length_define.length, command_id.length);
System.arraycopy(message_body, 0, messageByte, body_total_length_define.length+command_id.length, message_body.length);
System.arraycopy(reserve, 0, messageByte, body_total_length_define.length+command_id.length+message_body.length, reserve.length);
System.arraycopy(sequence_id, 0, messageByte, body_total_length_define.length+command_id.length+message_body.length+reserve.length, sequence_id.length);
System.arraycopy(uuid, 0, messageByte, body_total_length_define.length+command_id.length+message_body.length+reserve.length+sequence_id.length, uuid.length);
return messageByte;
}
我们还可以使用ByteBuffer来实现这一功能:
public static byte[] getMessageByte1(MessageEntity message) {
byte[] body_total_length_define = message.getBody_total_length_define();
byte[] command_id= message.getCommand_id();
byte[] message_body= message.getMessage_body();
byte[] reserve= message.getReserve();
byte[] sequence_id= message.getSequence_id();
byte[] uuid= message.getUuid();
int message_length = body_total_length_define.length+command_id.length+
message_body.length+reserve.length+sequence_id.length+uuid.length;
ByteBuffer bf = ByteBuffer.allocate(message_length);
bf.put(body_total_length_define);
bf.put(command_id);
bf.put(message_body);
bf.put(reserve);
bf.put(sequence_id);
bf.put(uuid);
return bf.array();
}
两种方式的复杂程度相比差异很大,第一种方式非常的繁琐,代码非常多,因此容易出现错误,而且效率又低,占用的内存又多,而第二种方式则相对简单很多,只需要为ByteBuffer赋好了初始值,然后把数组向里面put就完了,非常简单,效率当然更高,因为它的整个过程中就只是使用了一个ByteBuffer对象,而上一个方法里面则生成了好多对象,占内存大,效率低,因此第二种是最佳的方式。