Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question

migrated from stackoverflow.com Apr 12 at 20:32

This question came from our site for professional and enthusiast programmers.

2 Answers 2

up vote 4 down vote accepted

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];
    ...
}
share|improve this answer
    
@NexusDuck using new String in this case is necessary, because an array's toString just prints the object address, not the content. –  David Wallace Apr 11 at 20:03
    
@DavidWallace I had no idea. Disregard my comment then –  NexusDuck Apr 11 at 20:05

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;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.