HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Concatenate two arrays generated randomly

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
generatedarraysconcatenaterandomlytwo

Problem

I have written the code to concatenate two arrays . Please let me know of any loopholes in the written code.

import java.util.Random;
import java.util.Scanner;

public class ConcatArr {
    static Random rand = new Random();
    static Scanner in = new Scanner(System.in);
    public static void main(String[] args){
        System.out.println("Main Method Started");
        System.out.println("Initialize the 1st array");
        int[] arr1 = initArr();
        System.out.println("The element of the 1st array");
        print(arr1);
        System.out.println("Initialize the 1st array");
        int [] arr2 = initArr();
        System.out.println("The element of the 2nd array");
        print(arr2);
        int[] contArr = concatArr(arr1,arr2);
        System.out.println("Concatnated array");
        print(contArr);
        System.out.println("Main Method Ended");
    }
    public static void print(int[] arr){
        System.out.print("{");
        for(int val:arr){
            System.out.print(val + "  ");
        }
        System.out.print("}");
        System.out.println();
    }
    public static int[] initArr(){
        System.out.println("Enter the limit of the array");
        int limit = in.nextInt();
        System.out.println("Enter the maximum value of the array");
        int maxValue = in.nextInt();
        int[] arr = new int[limit];
        for(int i=0;i<limit;i++){
            arr[i] = rand.nextInt(maxValue);
        }
        return arr;
    }
    public static int[] concatArr(int[] arr1,int[] arr2){
        int[] tempArr = new int[arr1.length+arr2.length];
        for(int i=0;i<arr1.length;i++){
            tempArr[i] = arr1[i];
        }
        for(int j=0;j<arr2.length;j++){
            tempArr[j+arr1.length] = arr2[j];
        }
        return tempArr;
    }
}

Solution

Use the native method arraycopy as opposed to manually copying the elements for your concatenation method for better performance:

public static int[] concat(int[] a, int[] b) {
   int aLen = a.length;
   int bLen = b.length;
   int[] c= new int[aLen+bLen];
   System.arraycopy(a, 0, c, 0, aLen);
   System.arraycopy(b, 0, c, aLen, bLen);
   return c;
}


Also think about making more use of enhanced for loops, how come you are only using them for part of your solution and not the rest?

for(int i:arr){
    i = rand.nextInt(maxValue);
}

Code Snippets

public static int[] concat(int[] a, int[] b) {
   int aLen = a.length;
   int bLen = b.length;
   int[] c= new int[aLen+bLen];
   System.arraycopy(a, 0, c, 0, aLen);
   System.arraycopy(b, 0, c, aLen, bLen);
   return c;
}
for(int i:arr){
    i = rand.nextInt(maxValue);
}

Context

StackExchange Code Review Q#80006, answer score: 4

Revisions (0)

No revisions yet.