Java Collection Hash hashCode(Collection c)

Here you can find the source of hashCode(Collection c)

Description

Computes a hash code over c independent of the underlying Collection implementation.

License

Apache License

Parameter

Parameter Description
c any Collection

Return

the hash code of the Collection

Declaration

public static int hashCode(Collection c) 

Method Source Code

//package com.java2s;
/*/* ww  w .j a v a2  s.co  m*/
 * Copyright 2014 Johns Hopkins University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class Main {
    /**
     * Computes a hash code over {@code c} independent of the underlying {@code Collection} implementation.
     * <p>
     * It is the intent of this method to comply with the {@link Object#hashCode()} contract.
     *
     * @param c any Collection
     * @return the hash code of the Collection
     */
    public static int hashCode(Collection c) {
        int[] codes = new int[c.size()];

        // Different implementations will return an Iterator that returns hash codes in different orders
        // We keep the hash codes, order them, and then compute the final hash code.
        Iterator itr = c.iterator();
        int i = 0;
        while (itr.hasNext()) {
            codes[i++] = itr.next().hashCode();
        }

        Arrays.sort(codes);

        int prime = 53;
        int result = prime;

        for (int code : codes) {
            result = prime * result + code;
        }

        return result;
    }
}

Related

  1. hashCode(Collection collection)
  2. hashCode(Collection collection)
  3. hashCodeDeep(Collection collection)
  4. hashCodeUnordered(Collection collection)