Friday 4 November 2022

Generic method to concatenate two arrays in Java

Write a generic method to concatenate the two array elements. Method signature can be like below.

public static <T> T[] concatArrays(T[] a, T[] b) {
	.......
	.......	
}

 

concatArray method should return

1.   ‘a’ if the array ‘b’ is null or empty

2.   ‘b’ if the array ‘a’ is null or empty

3.   Else return a new array that contain the elements of a followed by the b array elements.

 

Find the below working application.


 

ArraysConcat.java

package com.sample.app.arrays;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ArraysConcat {

	/**
	 * 
	 * @param <T>
	 * @param a
	 * @param b
	 * 
	 * @return 1. Return a if b is null or empty. 2. Return b if a is null or empty.
	 *         3. Return new array that contain the elements of a followed by the b
	 *         array elements
	 */
	public static <T> T[] concatArrays(final T[] a, final T[] b) {

		if (a == null || a.length == 0) {
			return b;
		}

		if (b == null || b.length == 0) {
			return a;
		}

		int aLen = a.length;
		int bLen = b.length;

		@SuppressWarnings("unchecked")
		T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
		System.arraycopy(a, 0, c, 0, aLen);
		System.arraycopy(b, 0, c, aLen, bLen);

		return c;
	}

	public static void main(String[] args) {
		Integer[] evenNumbers = { 2, 4, 6, 8 };
		Integer[] oddNumbers = { 1, 3, 5, 7 };
		Integer[] emptyArray = {};

		System.out.println(Arrays.toString(concatArrays(evenNumbers, oddNumbers)));
		System.out.println(Arrays.toString(concatArrays(evenNumbers, emptyArray)));
		System.out.println(Arrays.toString(concatArrays(emptyArray, oddNumbers)));

	}

}

Output

[2, 4, 6, 8, 1, 3, 5, 7]
[2, 4, 6, 8]
[1, 3, 5, 7]


You may like

Interview Questions

Array programs in Java

Quick guide to load balancers

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

No comments:

Post a Comment