Arrays are objects in java. Every object in java has a class associated with it. By
using the class, we can check whether the array is of primitive type or not.
I
would recommend you go through my tutorial to know about the class of the array.
Is array a primitive
type or object in java?
Below
program checks whether an array is a primitive type array or not.
package com.sample.test; import java.util.HashSet; import java.util.Set; public class Test { private static final Set<Class<?>> PRIMITIVE_CLASSES = new HashSet<>(); static { loadPrimitiveClasses(); } private static void loadPrimitiveClasses() { PRIMITIVE_CLASSES.add(new byte[0].getClass()); PRIMITIVE_CLASSES.add(new short[0].getClass()); PRIMITIVE_CLASSES.add(new int[0].getClass()); PRIMITIVE_CLASSES.add(new long[0].getClass()); PRIMITIVE_CLASSES.add(new float[0].getClass()); PRIMITIVE_CLASSES.add(new double[0].getClass()); PRIMITIVE_CLASSES.add(new boolean[0].getClass()); PRIMITIVE_CLASSES.add(new char[0].getClass()); } public static boolean isprimitiveArray(Class<?> clazz) { if (clazz == null) { throw new IllegalArgumentException("clazz shouldn't be null"); } return PRIMITIVE_CLASSES.contains(clazz); } private static class Employee { } public static void main(String args[]) { int arr[] = new int[10]; Employee emps[] = new Employee[10]; System.out.println("is arr primitive? : " + isprimitiveArray(arr.getClass())); System.out.println("is emps primitive? : " + isprimitiveArray(emps.getClass())); } }
Output
is
arr primitive? : true
is emps primitive? : false
No comments:
Post a Comment