Sunday, 27 May 2018

Check whether an array is a primitive wrapper array or not

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.

Below program checks whether an array is a primitive wrapper array or not.

Test.java

package com.sample.test;

import java.util.HashSet;
import java.util.Set;

public class Test {

 private static final Set<Class<?>> PRIMITIVE_WRAPPER_CLASSES = new HashSet<>();

 static {
  loadPrimitiveWrapperClasses();
 }

 private static void loadPrimitiveWrapperClasses() {
  PRIMITIVE_WRAPPER_CLASSES.add(new Byte[0].getClass());
  PRIMITIVE_WRAPPER_CLASSES.add(new Short[0].getClass());
  PRIMITIVE_WRAPPER_CLASSES.add(new Integer[0].getClass());
  PRIMITIVE_WRAPPER_CLASSES.add(new Long[0].getClass());
  PRIMITIVE_WRAPPER_CLASSES.add(new Float[0].getClass());
  PRIMITIVE_WRAPPER_CLASSES.add(new Double[0].getClass());
  PRIMITIVE_WRAPPER_CLASSES.add(new Boolean[0].getClass());
  PRIMITIVE_WRAPPER_CLASSES.add(new Character[0].getClass());
 }

 public static boolean isprimitiveWrapperArray(Class<?> clazz) {
  if (clazz == null) {
   throw new IllegalArgumentException("clazz shouldn't be null");
  }
  return PRIMITIVE_WRAPPER_CLASSES.contains(clazz);
 }

 private static class Employee {

 }

 public static void main(String args[]) {
  int intArr[] = new int[10];
  Integer intWrapperArr[] = new Integer[10];

  Employee emps[] = new Employee[10];

  System.out.println("is intArr wrapper array? : " + isprimitiveWrapperArray(intArr.getClass()));
  System.out.println("is intWrapperArr wrapper array? : " + isprimitiveWrapperArray(intWrapperArr.getClass()));
  System.out.println("is emps wrapper array? : " + isprimitiveWrapperArray(emps.getClass()));
 }
}


Output

is intArr wrapper array? : false
is intWrapperArr wrapper array? : true
is emps wrapper array? : false





Previous                                                 Next                                                 Home

No comments:

Post a Comment