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.jcs.utils.struct.LRUMap.java

/**
 * Checks to see if all the items that should be in the cache are. Checks consistency between
 * List and map./*w ww .  j av  a2 s  .  co  m*/
 */
protected void verifyCache() {
    if (!log.isDebugEnabled()) {
        return;
    }

    boolean found = false;
    log.debug("verifycache: mapContains " + map.size() + " elements, linked list contains " + dumpCacheSize()
            + " elements");
    log.debug("verifycache: checking linked list by key ");
    for (LRUElementDescriptor li = (LRUElementDescriptor) list
            .getFirst(); li != null; li = (LRUElementDescriptor) li.next) {
        Object key = li.getKey();
        if (!map.containsKey(key)) {
            log.error("verifycache: map does not contain key : " + li.getKey());
            log.error("li.hashcode=" + li.getKey().hashCode());
            log.error("key class=" + key.getClass());
            log.error("key hashcode=" + key.hashCode());
            log.error("key toString=" + key.toString());
            if (key instanceof GroupAttrName) {
                GroupAttrName name = (GroupAttrName) key;
                log.error("GroupID hashcode=" + name.groupId.hashCode());
                log.error("GroupID.class=" + name.groupId.getClass());
                log.error("AttrName hashcode=" + name.attrName.hashCode());
                log.error("AttrName.class=" + name.attrName.getClass());
            }
            dumpMap();
        } else if (map.get(li.getKey()) == null) {
            log.error("verifycache: linked list retrieval returned null for key: " + li.getKey());
        }
    }

    log.debug("verifycache: checking linked list by value ");
    for (LRUElementDescriptor li3 = (LRUElementDescriptor) list
            .getFirst(); li3 != null; li3 = (LRUElementDescriptor) li3.next) {
        if (map.containsValue(li3) == false) {
            log.error("verifycache: map does not contain value : " + li3);
            dumpMap();
        }
    }

    log.debug("verifycache: checking via keysets!");
    for (Iterator itr2 = map.keySet().iterator(); itr2.hasNext();) {
        found = false;
        Serializable val = null;
        try {
            val = (Serializable) itr2.next();
        } catch (NoSuchElementException nse) {
            log.error("verifycache: no such element exception");
        }

        for (LRUElementDescriptor li2 = (LRUElementDescriptor) list
                .getFirst(); li2 != null; li2 = (LRUElementDescriptor) li2.next) {
            if (val.equals(li2.getKey())) {
                found = true;
                break;
            }
        }
        if (!found) {
            log.error("verifycache: key not found in list : " + val);
            dumpCacheEntries();
            if (map.containsKey(val)) {
                log.error("verifycache: map contains key");
            } else {
                log.error("verifycache: map does NOT contain key, what the HECK!");
            }
        }
    }
}

From source file:org.red5.server.so.SharedObject.java

/**
 * Set value of attribute with given name
 * @param name         Attribute name/*w  ww  .  j av  a  2  s .  co m*/
 * @param value        Attribute value
 * @return             <code>true</code> if there's such attribute and value was set, <code>false</code> otherwise
 */
public synchronized boolean setAttribute(String name, Object value) {
    ownerMessage.addEvent(Type.CLIENT_UPDATE_ATTRIBUTE, name, null);
    Object old = data.get(name);
    Integer oldHash = (value != null ? value.hashCode() : 0);
    if (old == null || !old.equals(value) || !oldHash.equals(hashes.get(name))) {
        modified = true;
        data.put(name, value);
        // only sync if the attribute changed
        syncEvents.add(new SharedObjectEvent(Type.CLIENT_UPDATE_DATA, name, value));
        notifyModified();
        changeStats.incrementAndGet();
        return true;
    } else {
        notifyModified();
        return false;
    }
}

From source file:ArraySet.java

private final Entry<K, V> removeMap(Object key) {
    int hashCode = 0;
    int index = 0;

    if (key != null) {
        hashCode = key.hashCode();
        index = (hashCode & 0x7FFFFFFF) % mapTable.length;
        for (Entry<K, V> e = mapTable[index], prev = null; e != null; prev = e, e = e.next) {
            if ((e.hashCode == hashCode) && key.equals(e.key)) {
                if (prev != null) {
                    prev.next = e.next;//from www  .  j  a  va  2s .  c  o  m
                } else {
                    mapTable[index] = e.next;
                }
                return e;
            }
        }
    } else {
        for (Entry<K, V> e = mapTable[index], prev = null; e != null; prev = e, e = e.next) {
            if ((e.hashCode == hashCode) && e.key == null) {
                if (prev != null) {
                    prev.next = e.next;
                } else {
                    mapTable[index] = e.next;
                }
                return e;
            }
        }
    }
    return null;
}

From source file:org.mule.tck.AbstractMuleTestCase.java

/**
 * A convenience method that will register an object in the registry using its hashcode as the key.  This will cause the object
 * to have any objects injected and lifecycle methods called.  Note that the object lifecycle will be called to the same current
 * lifecycle as the MuleContext//from   ww  w . ja v  a 2s.com
 *
 * @param o the object to register and initialize it
 * @throws RegistrationException
 */
protected void initialiseObject(Object o) throws RegistrationException {
    muleContext.getRegistry().registerObject(String.valueOf(o.hashCode()), o);
}

From source file:cn.remex.core.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.//  ww  w  .  jav  a 2s  .  c om
 * @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(final Object obj) {
    if (obj == null) {
        return 0;
    }
    if (obj.getClass().isArray()) {
        if (obj instanceof Object[]) {
            return nullSafeHashCode((Object[]) obj);
        }
        if (obj instanceof boolean[]) {
            return nullSafeHashCode((boolean[]) obj);
        }
        if (obj instanceof byte[]) {
            return nullSafeHashCode((byte[]) obj);
        }
        if (obj instanceof char[]) {
            return nullSafeHashCode((char[]) obj);
        }
        if (obj instanceof double[]) {
            return nullSafeHashCode((double[]) obj);
        }
        if (obj instanceof float[]) {
            return nullSafeHashCode((float[]) obj);
        }
        if (obj instanceof int[]) {
            return nullSafeHashCode((int[]) obj);
        }
        if (obj instanceof long[]) {
            return nullSafeHashCode((long[]) obj);
        }
        if (obj instanceof short[]) {
            return nullSafeHashCode((short[]) obj);
        }
    }
    return obj.hashCode();
}

From source file:org.mule.tck.AbstractMuleTestCase.java

/**
 * Create an object of instance <code>clazz</code>. It will then register the object with the registry so that any
 * dependencies are injected and then the object will be initialised.
 * Note that if the object needs to be configured with additional state that cannot be passed into the constructor you should
 * create an instance first set any additional data on the object then call {@link #initialiseObject(Object)}.
 *
 * @param clazz the class to create an instance of.
 * @param args  constructor parameters//from www . ja  v a2  s .com
 * @param <T>   Object of this type will be returned
 * @return an initialised instance of <code>class</code>
 * @throws Exception if there is a problem creating or initializing the object
 */
@SuppressWarnings("unchecked")
protected <T extends Object> T createObject(Class<T> clazz, Object... args) throws Exception {
    if (args == null) {
        args = ClassUtils.NO_ARGS;
    }
    Object o = ClassUtils.instanciateClass(clazz, args);
    muleContext.getRegistry().registerObject(String.valueOf(o.hashCode()), o);
    return (T) o;
}

From source file:IntHashMap.java

/**
 * Returns a collection view of the mappings contained in this map. Each
 * element in the returned collection is a <code>Map.Entry</code>. The
 * collection is backed by the map, so changes to the map are reflected in
 * the collection, and vice-versa. The collection supports element removal,
 * which removes the corresponding mapping from the map, via the
 * <code>Iterator.remove</code>, <code>Collection.remove</code>,
 * <code>removeAll</code>, <code>retainAll</code>, and <code>clear</code>
 * operations. It does not support the <code>add</code> or
 * <code>addAll</code> operations.
 *
 * @return a collection view of the mappings contained in this map.
 * @see java.util.Map.Entry//from  ww w . j  a v a 2 s  .  c  o m
 */
@Override
public Set entrySet() {
    if (entrySet == null) {
        entrySet = new AbstractSet() {
            @Override
            public Iterator iterator() {
                return new IntHashIterator(ENTRIES);
            }

            @Override
            public boolean contains(Object o) {
                if (!(o instanceof Map.Entry)) {
                    return false;
                }
                Map.Entry entry = (Map.Entry) o;
                Object key = entry.getKey();
                Entry tab[] = table;
                int hash = (key == null ? 0 : key.hashCode());
                int index = (hash & 0x7FFFFFFF) % tab.length;

                for (Entry e = tab[index]; e != null; e = e.next) {
                    if (e.key == hash && e.equals(entry)) {
                        return true;
                    }
                }
                return false;
            }

            @Override
            public boolean remove(Object o) {
                if (!(o instanceof Map.Entry)) {
                    return false;
                }
                Map.Entry entry = (Map.Entry) o;
                Object key = entry.getKey();
                Entry tab[] = table;
                int hash = (key == null ? 0 : key.hashCode());
                int index = (hash & 0x7FFFFFFF) % tab.length;

                for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.next) {
                    if (e.key == hash && e.equals(entry)) {
                        modCount++;
                        if (prev != null) {
                            prev.next = e.next;
                        } else {
                            tab[index] = e.next;
                        }

                        count--;
                        e.value = null;
                        return true;
                    }
                }
                return false;
            }

            @Override
            public int size() {
                return count;
            }

            @Override
            public void clear() {
                IntHashMap.this.clear();
            }
        };
    }

    return entrySet;
}

From source file:Main.java

public static int hashCode(Object target) {
    if (target == null)
        return 0;
    final int prime = 31;
    int result = 1;

    Class<?> current = target.getClass();
    do {// w w w . j  av a  2  s. co m
        for (Field f : current.getDeclaredFields()) {
            if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())
                    || f.isSynthetic()) {
                continue;
            }

            Object self;
            try {
                f.setAccessible(true);
                self = f.get(target);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
            if (self == null) {
                result = prime * result + 0;
            } else if (self.getClass().isArray()) {
                if (self.getClass().equals(boolean[].class)) {
                    result = prime * result + Arrays.hashCode((boolean[]) self);
                } else if (self.getClass().equals(char[].class)) {
                    result = prime * result + Arrays.hashCode((char[]) self);
                } else if (self.getClass().equals(byte[].class)) {
                    result = prime * result + Arrays.hashCode((byte[]) self);
                } else if (self.getClass().equals(short[].class)) {
                    result = prime * result + Arrays.hashCode((short[]) self);
                } else if (self.getClass().equals(int[].class)) {
                    result = prime * result + Arrays.hashCode((int[]) self);
                } else if (self.getClass().equals(long[].class)) {
                    result = prime * result + Arrays.hashCode((long[]) self);
                } else if (self.getClass().equals(float[].class)) {
                    result = prime * result + Arrays.hashCode((float[]) self);
                } else if (self.getClass().equals(double[].class)) {
                    result = prime * result + Arrays.hashCode((double[]) self);
                } else {
                    result = prime * result + Arrays.hashCode((Object[]) self);
                }
            } else {
                result = prime * result + self.hashCode();
            }

            System.out.println(f.getName() + ": " + result);
        }
        current = current.getSuperclass();
    } while (!Object.class.equals(current));

    return result;
}

From source file:org.apache.bookkeeper.common.util.OrderedExecutor.java

public ExecutorService chooseThread(Object orderingKey) {
    // skip hashcode generation in this special case
    if (threads.length == 1) {
        return threads[0];
    }//w  w  w .  j  ava2 s.  c  o  m

    if (null == orderingKey) {
        return threads[rand.nextInt(threads.length)];
    } else {
        return threads[MathUtils.signSafeMod(orderingKey.hashCode(), threads.length)];
    }
}

From source file:org.openfaces.component.table.TableDataModel.java

private static boolean checkSerializableEqualsAndHashcode(Object rowKey) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Object deserializedRowKey;
    try {// w  ww. j  a  v a  2s  .  c  o m
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(rowKey);
        oos.close();
        byte[] serializedObject = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(serializedObject);
        ObjectInputStream ois = new ObjectInputStream(bais);
        deserializedRowKey = ois.readObject();
        bais.close();
    } catch (IOException e) {
        throw new RuntimeException(
                "The rowData or rowKey object is marked as Serializable but can't be serialized: "
                        + rowKey.getClass().getName()
                        + " ; check that all object's fields are also Serializable",
                e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    boolean equalsValid = deserializedRowKey.equals(rowKey);
    boolean hashCodeValid = deserializedRowKey.hashCode() == rowKey.hashCode();
    boolean result = equalsValid && hashCodeValid;
    return result;
}