Example usage for java.lang Object hashCode

List of usage examples for java.lang Object hashCode

Introduction

In this page you can find the example usage for java.lang Object hashCode.

Prototype

@HotSpotIntrinsicCandidate
public native int hashCode();

Source Link

Document

Returns a hash code value for the object.

Usage

From source file:org.apache.crunch.types.avro.Avros.java

private static int reflectAwareHashCode(Object o, Schema s, AvroMode mode) {
    if (o == null)
        return 0; // incomplete datum
    int hashCode = 1;
    switch (s.getType()) {
    case RECORD:/*from   w  w  w .j  a v a  2  s.  c  o  m*/
        for (Schema.Field f : s.getFields()) {
            if (f.order() == Schema.Field.Order.IGNORE)
                continue;
            hashCode = hashCodeAdd(hashCode, mode.getData().getField(o, f.name(), f.pos()), f.schema(), mode);
        }
        return hashCode;
    case ARRAY:
        Collection<?> a = (Collection<?>) o;
        Schema elementType = s.getElementType();
        for (Object e : a)
            hashCode = hashCodeAdd(hashCode, e, elementType, mode);
        return hashCode;
    case UNION:
        return reflectAwareHashCode(o, s.getTypes().get(mode.getData().resolveUnion(s, o)), mode);
    case ENUM:
        return s.getEnumOrdinal(o.toString());
    case NULL:
        return 0;
    case STRING:
        return (o instanceof Utf8 ? o : new Utf8(o.toString())).hashCode();
    default:
        return o.hashCode();
    }
}

From source file:ArrayUtils.java

/**
 * A compliment to the {@link #equals(Object, Object)} method, this method
 * returns a hashcode for <code>array</code> such that it is consistent with
 * the equals contract for the {@link Object#equals(Object)} method,
 * represented by the {@link #equals(Object, Object)} method.
 * /*from  w w w .  j a  v a  2  s  .co  m*/
 * @param array
 *            The array to get a hashcode for
 * @return A hashcode based on <code>array</code> and its contents, if any
 */
public static int hashCode(Object array) {
    if (array == null)
        return 0;
    if (!array.getClass().isArray())
        return array.hashCode();
    int ret = array.getClass().getComponentType().hashCode();
    int len = Array.getLength(array);
    for (int i = 0; i < len; i++) {
        ret *= hashCode(Array.get(array, i));
        ret += 29;
    }
    return ret;
}

From source file:com.opensymphony.oscache.base.algorithm.AbstractConcurrentReadCache.java

/**
 * Return hash code for Object x./* w  w w .  j  a v  a  2s  . com*/
 * Since we are using power-of-two
 * tables, it is worth the effort to improve hashcode via
 * the same multiplicative scheme as used in IdentityHashMap.
 */
private static int hash(Object x) {
    int h = x.hashCode();

    // Multiply by 127 (quickly, via shifts), and mix in some high
    // bits to help guard against bunching of codes that are
    // consecutive or equally spaced.
    return ((h << 7) - h + (h >>> 9) + (h >>> 17));
}

From source file:cloudnet.util.Dumper.java

/**
 *
 * @param o//from   www . ja  v  a 2  s  .  c o m
 * @param ctx
 * @return
 */
protected static String dump(Object o, DumpContext ctx) {
    if (o == null) {
        return "<null>";
    }

    ctx.callCount++;
    StringBuilder tabs = new StringBuilder();
    for (int k = 0; k < ctx.callCount; k++) {
        tabs.append("\t");
    }
    StringBuilder buffer = new StringBuilder();
    Class oClass = o.getClass();

    String oSimpleName = getSimpleNameWithoutArrayQualifier(oClass);

    if (ctx.ignoreList.get(oSimpleName + ":") != null) {
        return "<Ignored>";
    }

    if (oClass.isArray()) {
        buffer.append("\n");
        buffer.append(tabs.toString().substring(1));
        buffer.append("[\n");
        int rowCount = ctx.maxArrayElements == 0 ? Array.getLength(o)
                : FastMath.min(ctx.maxArrayElements, Array.getLength(o));
        for (int i = 0; i < rowCount; i++) {
            buffer.append(tabs.toString());
            try {
                Object value = Array.get(o, i);
                buffer.append(dumpValue(value, ctx));
            } catch (Exception e) {
                buffer.append(e.getMessage());
            }
            if (i < Array.getLength(o) - 1) {
                buffer.append(",");
            }
            buffer.append("\n");
        }
        if (rowCount < Array.getLength(o)) {
            buffer.append(tabs.toString());
            buffer.append(Array.getLength(o) - rowCount + " more array elements...");
            buffer.append("\n");
        }
        buffer.append(tabs.toString().substring(1));
        buffer.append("]");
    } else {
        buffer.append("\n");
        buffer.append(tabs.toString().substring(1));
        buffer.append("{\n");
        buffer.append(tabs.toString());
        buffer.append("hashCode: " + o.hashCode());
        buffer.append("\n");
        while (oClass != null && oClass != Object.class) {
            Field[] fields = oClass.getDeclaredFields();

            if (ctx.ignoreList.get(oClass.getSimpleName()) == null) {
                if (oClass != o.getClass()) {
                    buffer.append(tabs.toString().substring(1));
                    buffer.append("  Inherited from superclass " + oSimpleName + ":\n");
                }

                for (int i = 0; i < fields.length; i++) {

                    String fSimpleName = getSimpleNameWithoutArrayQualifier(fields[i].getType());
                    String fName = fields[i].getName();

                    fields[i].setAccessible(true);
                    buffer.append(tabs.toString());
                    buffer.append(fName + "(" + fSimpleName + ")");
                    buffer.append("=");

                    if (ctx.ignoreList.get(":" + fName) == null
                            && ctx.ignoreList.get(fSimpleName + ":" + fName) == null
                            && ctx.ignoreList.get(fSimpleName + ":") == null) {

                        try {
                            Object value = fields[i].get(o);
                            buffer.append(dumpValue(value, ctx));
                        } catch (Exception e) {
                            buffer.append(e.getMessage());
                        }
                        buffer.append("\n");
                    } else {
                        buffer.append("<Ignored>");
                        buffer.append("\n");
                    }
                }
                oClass = oClass.getSuperclass();
                oSimpleName = oClass.getSimpleName();
            } else {
                oClass = null;
                oSimpleName = "";
            }
        }
        buffer.append(tabs.toString().substring(1));
        buffer.append("}");
    }
    ctx.callCount--;
    return buffer.toString();
}

From source file:dkf.model.object.ObjectClassModelManager.java

public void publish(Object element, String name) throws RTIinternalError, NameNotFound,
        FederateNotExecutionMember, NotConnected, InvalidObjectClassHandle, InstantiationException,
        IllegalAccessException, AttributeNotDefined, ObjectClassNotDefined, SaveInProgress, RestoreInProgress,
        IllegalName, ObjectInstanceNameInUse, ObjectInstanceNameNotReserved, ObjectClassNotPublished,
        AttributeNotOwned, ObjectInstanceNotKnown, UpdateException {

    ObjectClassModel ocm = published.get(element.getClass().getAnnotation(ObjectClass.class).name());

    if (ocm == null) {
        ocm = new ObjectClassModel(element.getClass());
        ocm.publish();/*  w  w w  . j  ava2  s  . c  om*/
        this.published.put(element.getClass().getAnnotation(ObjectClass.class).name(), ocm);
    }

    ObjectClassEntity entity = null;
    if (name != null)
        entity = new ObjectClassEntity(name, element);
    else
        entity = new ObjectClassEntity(element.getClass().getName() + element.hashCode(), element);

    ocm.addEntity(entity);
    this.mapInstanceNameObjectClassEntity.put(entity.getInstanceName(), entity);

}

From source file:SoftValueMap.java

/**
 * Updates the table to map 'key' to 'value'. Any existing mapping is overwritten.
 *
 * @param key mapping key [may not be null].
 * @param value mapping value [may not be null].
 *
 * @return Object previous value mapping for 'key' [null if no previous mapping
 * existed or its value has been cleared by the garbage collector and removed from the table].
 *//*from  w w w. j a v  a2 s . c o m*/
public Object put(final Object key, final Object value) {
    if (key == null)
        throw new IllegalArgumentException("null input: key");
    if (value == null)
        throw new IllegalArgumentException("null input: value");

    if ((++m_writeAccessCount % m_writeClearCheckFrequency) == 0)
        removeClearedValues();

    SoftEntry currentKeyEntry = null;

    // detect if 'key' is already in the table [in which case, set 'currentKeyEntry' to point to its entry]:

    // index into the corresponding hash bucket:
    final int keyHashCode = key.hashCode();
    SoftEntry[] buckets = m_buckets;
    int bucketIndex = (keyHashCode & 0x7FFFFFFF) % buckets.length;

    // traverse the singly-linked list of entries in the bucket:
    for (SoftEntry entry = buckets[bucketIndex]; entry != null; entry = entry.m_next) {
        final Object entryKey = entry.m_key;

        if (IDENTITY_OPTIMIZATION) {
            // note: this uses an early identity comparison opimization, making this a bit
            // faster for table keys that do not override equals() [Thread, etc]
            if ((key == entryKey) || ((keyHashCode == entryKey.hashCode()) && key.equals(entryKey))) {
                currentKeyEntry = entry;
                break;
            }
        } else {
            if ((keyHashCode == entryKey.hashCode()) && key.equals(entryKey)) {
                currentKeyEntry = entry;
                break;
            }
        }
    }

    if (currentKeyEntry != null) {
        // replace the current value:

        final IndexedSoftReference ref = currentKeyEntry.m_softValue;
        final Object currentKeyValue = ref.get(); // can be null already [no need to work around the get() bug, though]

        if (currentKeyValue == null)
            ref.m_bucketIndex = -1; // disable removal by removeClearedValues() [need to do this because of the identity comparison there]
        currentKeyEntry.m_softValue = new IndexedSoftReference(value, m_valueReferenceQueue, bucketIndex);

        return currentKeyValue; // may return null to the caller
    } else {
        // add a new entry:

        if (m_size >= m_sizeThreshold)
            rehash();

        // recompute the hash bucket index:
        buckets = m_buckets;
        bucketIndex = (keyHashCode & 0x7FFFFFFF) % buckets.length;
        final SoftEntry bucketListHead = buckets[bucketIndex];
        final SoftEntry newEntry = new SoftEntry(m_valueReferenceQueue, key, value, bucketListHead,
                bucketIndex);
        buckets[bucketIndex] = newEntry;

        ++m_size;

        return null;
    }
}

From source file:org.asoem.greyfish.utils.collect.BitString.java

@Override
public final int hashCode() {
    int hashCode = 1;
    for (Object o : this.asIndices()) {
        hashCode = 31 * hashCode + o.hashCode();

        hashCode = ~~hashCode;/*from w  ww  . j  a v a 2 s  .  c  o  m*/
        // needed to deal with GWT integer overflow
    }
    hashCode = 31 * hashCode + size();
    return hashCode;
}

From source file:org.briljantframework.data.vector.AbstractVector.java

@Override
public int hashCode() {
    int result = 1;
    for (int i = 0, size = size(); i < size; i++) {
        Object o = loc().get(Object.class, i);
        result += 31 * result + (!Is.NA(o) ? o.hashCode() : 0);
    }/*from ww  w  . ja v  a  2s.com*/
    return result;
}

From source file:org.structr.core.entity.AbstractRelationship.java

@Override
public boolean equals(final Object o) {

    return (o != null && new Integer(this.hashCode()).equals(new Integer(o.hashCode())));

}

From source file:org.batoo.common.util.ObjectUtils.java

/**
 * Return as hash code for the given object; typically the value of <code>{@link Object#hashCode()}</code>. If the object is an array,
 * this method will delegate to any of the <code>nullSafeHashCode</code> methods for arrays in this class. If the object is
 * <code>null</code>, this method returns 0.
 * //from  w  w w .  j av  a2  s.  co  m
 * @param obj
 *            the object value
 * @return the hash code
 * 
 * @see #nullSafeHashCode(Object[])
 * @see #nullSafeHashCode(boolean[])
 * @see #nullSafeHashCode(byte[])
 * @see #nullSafeHashCode(char[])
 * @see #nullSafeHashCode(double[])
 * @see #nullSafeHashCode(float[])
 * @see #nullSafeHashCode(int[])
 * @see #nullSafeHashCode(long[])
 * @see #nullSafeHashCode(short[])
 */
public static int nullSafeHashCode(Object obj) {
    if (obj == null) {
        return 0;
    }
    if (obj.getClass().isArray()) {
        if (obj instanceof Object[]) {
            return ObjectUtils.nullSafeHashCode((Object[]) obj);
        }
        if (obj instanceof boolean[]) {
            return ObjectUtils.nullSafeHashCode((boolean[]) obj);
        }
        if (obj instanceof byte[]) {
            return ObjectUtils.nullSafeHashCode((byte[]) obj);
        }
        if (obj instanceof char[]) {
            return ObjectUtils.nullSafeHashCode((char[]) obj);
        }
        if (obj instanceof double[]) {
            return ObjectUtils.nullSafeHashCode((double[]) obj);
        }
        if (obj instanceof float[]) {
            return ObjectUtils.nullSafeHashCode((float[]) obj);
        }
        if (obj instanceof int[]) {
            return ObjectUtils.nullSafeHashCode((int[]) obj);
        }
        if (obj instanceof long[]) {
            return ObjectUtils.nullSafeHashCode((long[]) obj);
        }
        if (obj instanceof short[]) {
            return ObjectUtils.nullSafeHashCode((short[]) obj);
        }
    }
    return obj.hashCode();
}