2
\$\begingroup\$

I have this code that duplicates a byte array 5 times.

class Multiple {
 public static void main(String[] args) {
 byte[] result = new byte[] {0x41,0x42,0x43,0x44};
 int len = result.length;
 byte[] multipled = new byte[len*5];
 for (int i = 0; i < 5; i++) {
 for (int j = 0; j < len; j++) {
 multipled[i*len + j] = result[j];
 }
 } 
 System.out.println(new String(multipled));
 System.out.println(new String(result));
 }
}

Example:

ABCDABCDABCDABCDABCD
ABCD

The code uses multiple loops and assignment, can it be better or shorter?

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Apr 11, 2015 at 19:54
\$\endgroup\$
0

2 Answers 2

4
\$\begingroup\$

It can be made shorter:

public static void main(String[] args) {
 byte[] result = new byte[] {0x41, 0x42, 0x43, 0x44};
 byte[] multipled = new byte[result.length * 5];
 for (int i = 0; i < multipled.length; i++)
 multipled[i] = result[i % result.length];
 ...
}
answered Apr 11, 2015 at 19:58
\$\endgroup\$
2
  • \$\begingroup\$ @NexusDuck using new String in this case is necessary, because an array's toString just prints the object address, not the content. \$\endgroup\$ Commented Apr 11, 2015 at 20:03
  • \$\begingroup\$ @DavidWallace I had no idea. Disregard my comment then \$\endgroup\$ Commented Apr 11, 2015 at 20:05
2
\$\begingroup\$

This operation is worth defining as a function for clarity and reuse.

To copy an array, use System.arraycopy().

public static byte[] repeat(byte[] array, int times) {
 byte[] repeated = new byte[times * array.length];
 for (int dest = 0; dest < repeated.length; dest += array.length) {
 System.arraycopy(array, 0, repeated, dest, array.length);
 }
 return repeated;
}
answered Apr 13, 2015 at 1:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.