集册 Java实例教程 返回指定数组的适当哈希代码。

返回指定数组的适当哈希代码。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

510
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
返回指定数组的适当哈希代码。


//package com.nowjava;/** from N  o w  J a v a . c o m**/

import java.lang.reflect.Array;


public class Main {

    public static void main(String[] argv) throws Exception {

        Object array = "nowjava.com";

        System.out.println(computeHashCode(array));

    }


    /**

     * 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 &
展开阅读全文