hashing.java

来自「java 的源代码」· Java 代码 · 共 65 行

JAVA
65
字号
package com.reddragon2046.base.utilities.data.algorithms;

import com.reddragon2046.base.utilities.data.InputIterator;
import com.reddragon2046.base.utilities.data.util.IteratorFactory;
import java.util.Collection;

public final class Hashing
{

    private Hashing()
    {
    }

    public static int orderedHash(Collection c)
    {
        return orderedHash(IteratorFactory.start(c), IteratorFactory.finish(c));
    }

    private static int orderedHash(InputIterator first, InputIterator last)
    {
        if(!first.isCompatibleWith(last))
            throw new IllegalArgumentException("iterators not compatible");
        int h = 0;
        int length = first.distance(last);
        int position = 0;
        int skip = 1;
        if(length >= 16)
        {
            skip = length / 16;
            first.advance(length % 16);
        }
        for(InputIterator firstx = (InputIterator)first.clone(); !firstx.equals(last); firstx.advance(skip))
        {
            Object obj = firstx.get();
            if(obj != null)
                h ^= obj.hashCode() / (position % 16 + 1);
            position++;
        }

        return h;
    }

    public static int unorderedHash(Collection c)
    {
        return unorderedHash(IteratorFactory.start(c), IteratorFactory.finish(c));
    }

    private static int unorderedHash(InputIterator first, InputIterator last)
    {
        if(!first.isCompatibleWith(last))
            throw new IllegalArgumentException("iterators not compatible");
        int h = 0;
        for(InputIterator firstx = (InputIterator)first.clone(); !firstx.equals(last); firstx.advance())
        {
            Object obj = firstx.get();
            if(obj != null)
                h ^= obj.hashCode();
        }

        return h;
    }

    static final int HASH_SIZE = 16;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?