Java Array Hash Code hashCode(Object array)

Here you can find the source of hashCode(Object array)

Description

Computes a hash code for the given array based on its content instead of on its identity.

License

Apache License

Parameter

Parameter Description
array an array

Exception

Parameter Description
IllegalArgumentException if array is not actually an array

Return

a hash code for the given array based on its content

Declaration

public static int hashCode(Object array) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Arrays;

public class Main {
    /**//from  w  w w  .  j a  v  a2s.c o  m
     * Computes a hash code for the given array based on its content instead of on its identity. This
     * provides a convenience above and beyond similar methods in {@link Arrays} because it accepts
     * any array type, including primitive array types.
     *
     * @param array an array
     * @return a hash code for the given array based on its content
     * @throws IllegalArgumentException if {@code array} is not actually an array
     * 
     * @see Arrays#hashCode(Object[])
     */
    public static int hashCode(Object array) {
        Class<?> arrayType = array.getClass();
        if (!arrayType.isArray()) {
            throw new IllegalArgumentException("specified object is not an array");
        }
        Class<?> componentType = arrayType.getComponentType();
        if (componentType.isPrimitive()) {
            if (componentType == boolean.class) {
                return Arrays.hashCode((boolean[]) array);
            } else if (componentType == byte.class) {
                return Arrays.hashCode((byte[]) array);
            } else if (componentType == char.class) {
                return Arrays.hashCode((char[]) array);
            } else if (componentType == short.class) {
                return Arrays.hashCode((short[]) array);
            } else if (componentType == int.class) {
                return Arrays.hashCode((int[]) array);
            } else if (componentType == long.class) {
                return Arrays.hashCode((long[]) array);
            } else if (componentType == float.class) {
                return Arrays.hashCode((float[]) array);
            } else if (componentType == double.class) {
                return Arrays.hashCode((double[]) array);
            } else {
                throw new AssertionError("Unrecognized primitive type: " + componentType);
            }
        } else {
            return Arrays.hashCode((Object[]) array);
        }
    }
}

Related

  1. deepHashCode(double[][] matrix)
  2. hashCode(byte[] bytes)
  3. hashCode(byte[] obj)
  4. hashCode(final Object[] array1)
  5. hashCode(Map a)
  6. hashCode(Object array)
  7. hashCode(String[] names, Object[] values)
  8. printArray(byte[] array, boolean withHash)