Java examples for Collection Framework:Array Element
Returns a suitable hash code for the specified array.
//package com.java2s; import java.lang.reflect.Array; public class Main { public static void main(String[] argv) throws Exception { Object array = "java2s.com"; System.out.println(computeHashCode(array)); }/*from w w w . j ava 2s . co m*/ /** * Returns a suitable hash code for the specified array. If the passed * object is <code>null</code>, <code>0</code> is returned. * It is allowed to pass an object that is not an array, in this case, * the hash code of the object will be returned. Otherwise the hash code * will be based on the array elements. <code>null</code> elements are * allowed. * This method does not handle multidimensional arrays, i.e. if an * array contains another array, the hash code is based on identity. * @param array the array * @return a suitable hash code */ public static int computeHashCode(Object array) { if (null == array) return 0; if (!array.getClass().isArray()) return array.hashCode(); int length = Array.getLength(array); int hashCode = 17; for (int ii = 0; ii < length; ii++) { Object value = Array.get(array, ii); if (null != value) hashCode = (31 * hashCode) + value.hashCode(); } return hashCode; } }