最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What are java equivalents to JS push, concat, unshift? - Stack Overflow

programmeradmin2浏览0评论

I'm trying to convert the following JS to Java:

serializeSig:function(r,s){
var rBa=r.toByteArraySigned();
var sBa=s.toByteArraySigned();
var sequence=[];
sequence.push(2);
sequence.push(rBa.length);
sequence=sequence.concat(rBa);
sequence.push(2);
sequence.push(sBa.length);
sequence=sequence.concat(sBa);
sequence.unshift(sequence.length);
sequence.unshift(48);
return sequence
}

I think push would translate to add, concat to some kind of addAll, but what is unshift? And of what type would my variables in java be?

I'm trying to convert the following JS to Java:

serializeSig:function(r,s){
var rBa=r.toByteArraySigned();
var sBa=s.toByteArraySigned();
var sequence=[];
sequence.push(2);
sequence.push(rBa.length);
sequence=sequence.concat(rBa);
sequence.push(2);
sequence.push(sBa.length);
sequence=sequence.concat(sBa);
sequence.unshift(sequence.length);
sequence.unshift(48);
return sequence
}

I think push would translate to add, concat to some kind of addAll, but what is unshift? And of what type would my variables in java be?

Share Improve this question asked Feb 13, 2014 at 19:56 membersoundmembersound 87.1k218 gold badges675 silver badges1.2k bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

myArray.unshift(obj) corresponds to myList.add(0, obj).

A byte array in Java is byte[]. A list of byte arrays would be a List<byte[]>. (That's java.util.List, not java.awt.List, just in case you get the wrong import.)

EDIT: Looks like you are trying to create a byte array, not a list of byte arrays. In that case, you should use a java.nio.ByteBuffer, or possibly a java.io.ByteArrayOutputStream. The latter has to be written to sequentially -- you cannot do the equivalent of an unshift.

This looks like you are trying to use a ByteBuffer to serialize some data.

 public static void serialize(ByteBuffer bb, String r, String s) {
      bb.put(48);
      int start = bb.position();
      bb.put(0); // padding.
      bb.put(2);
      byte[] rBa = r.getBytes();
      bb.put((byte) rBa.length);
      bb.put(rBa);
      byte[] sBa = s.getBytes();
      bb.put((byte) sBa.length);
      bb.put(sBa);
      bb.put(start, (byte) (bb.position() - start - 1));
}

Using an List<Byte> is very inefficient and not supported by the packages which do IO.

You could use an arraylist of Bytes.

List<Byte> sequence = new ArrayList<>();

To add to the end of an arraylist use:

sequence.add(item);

To add to the front use:

sequence.add(0, item);
发布评论

评论列表(0)

  1. 暂无评论