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.engine.memory.lru.LRUMemoryCache.java

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

    boolean found = false;
    log.debug("verifycache[" + cacheName + "]: mapContains " + map.size() + " elements, linked list contains "
            + dumpCacheSize() + " elements");
    log.debug("verifycache: checking linked list by key ");
    for (MemoryElementDescriptor li = (MemoryElementDescriptor) list
            .getFirst(); li != null; li = (MemoryElementDescriptor) li.next) {
        Object key = li.ce.getKey();
        if (!map.containsKey(key)) {
            log.error("verifycache[" + cacheName + "]: map does not contain key : " + li.ce.getKey());
            log.error("li.hashcode=" + li.ce.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.ce.getKey()) == null) {
            log.error("verifycache[" + cacheName + "]: linked list retrieval returned null for key: "
                    + li.ce.getKey());
        }
    }

    log.debug("verifycache: checking linked list by value ");
    for (MemoryElementDescriptor li3 = (MemoryElementDescriptor) list
            .getFirst(); li3 != null; li3 = (MemoryElementDescriptor) li3.next) {
        if (map.containsValue(li3) == false) {
            log.error("verifycache[" + cacheName + "]: 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 (MemoryElementDescriptor li2 = (MemoryElementDescriptor) list
                .getFirst(); li2 != null; li2 = (MemoryElementDescriptor) li2.next) {
            if (val.equals(li2.ce.getKey())) {
                found = true;
                break;
            }
        }
        if (!found) {
            log.error("verifycache[" + cacheName + "]: 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.apache.ojb.broker.util.ReferenceMap.java

private int hashCode(Object obj) {
    return useSystemIdentity ? System.identityHashCode(obj) : obj.hashCode(); // null keys|values are not supported
}

From source file:com.wavemaker.json.JSONMarshallerTest.java

public void testValueTransformer() throws Exception {

    JSONState state = new JSONState();

    Map<String, Object> enclosed = new HashMap<String, Object>();
    enclosed.put("hi", "foo");

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("bar", enclosed);

    assertEquals("{\"bar\":{\"hi\":\"foo\"}}", JSONMarshaller.marshal(map, state));

    state.setValueTransformer(new ValueTransformer() {

        @Override// w w  w.  j a  v a2  s  . com
        public Tuple.Three<Object, FieldDefinition, Integer> transformToJSON(Object input,
                FieldDefinition fieldDefinition, int arrayLevel, Object root, String path,
                TypeState typeState) {

            if ("bar.hi".equals(path)) {
                GenericFieldDefinition fd = new GenericFieldDefinition();
                fd.setTypeDefinition(typeState.getType(String.class.getName()));
                return new Tuple.Three<Object, FieldDefinition, Integer>(
                        input + " transformed, root: " + root.hashCode(), fd, 0);
            } else if ("bar.bye".equals(path)) {
                GenericFieldDefinition fd = new GenericFieldDefinition();
                fd.setTypeDefinition(typeState.getType(Short.TYPE.getName()));
                return new Tuple.Three<Object, FieldDefinition, Integer>(12, fd, 0);
            } else {
                return null;
            }
        }

        @Override
        public Tuple.Three<Object, FieldDefinition, Integer> transformToJava(Object input,
                FieldDefinition fieldDefinition, int arrayLevel, Object root, String path,
                TypeState typeState) {

            // unused in this test
            return null;
        }
    });

    assertEquals("{\"bar\":{\"hi\":\"foo transformed, root: " + map.hashCode() + "\"}}",
            JSONMarshaller.marshal(map, state));

    enclosed.remove("hi");
    enclosed.put("bye", "fdks");
    assertEquals("{\"bar\":{\"bye\":12}}", JSONMarshaller.marshal(map, state));
}

From source file:com.googlecode.ehcache.annotations.key.MessageDigestCacheKeyGenerator.java

@Override
protected void appendHash(MessageDigestOutputStream generator, Object e) {
    if (e instanceof String) {
        generator.writeUTF((String) e);
    } else if (e instanceof Boolean) {
        generator.writeBoolean((Boolean) e);
    } else if (e instanceof Byte) {
        generator.writeByte((Byte) e);
    } else if (e instanceof Character) {
        generator.writeChar((Character) e);
    } else if (e instanceof Double) {
        generator.writeDouble((Double) e);
    } else if (e instanceof Float) {
        generator.writeFloat((Float) e);
    } else if (e instanceof Integer) {
        generator.writeInt((Integer) e);
    } else if (e instanceof Long) {
        generator.writeLong((Long) e);
    } else if (e instanceof Short) {
        generator.writeShort((Short) e);
    } else {//from   www .j av a2 s .  c o  m
        generator.writeInt(e.hashCode());
    }
}

From source file:com.google.gwt.emultest.java.util.HashMapTest.java

public void testIteration_withCollidingHashCodes() {

    Object firstKey = createObjectWithHashCode(1);
    Object secondKey = createObjectWithHashCode(1);

    // make sure we actually have a hash collision for this test
    assertEquals(firstKey.hashCode(), secondKey.hashCode());

    HashMap<Object, String> testMap = new HashMap<>();
    testMap.put(firstKey, "one");
    testMap.put(secondKey, "two");

    Iterator<Object> it = testMap.keySet().iterator();

    assertTrue("new iterator should have next", it.hasNext());
    Object keyFromMap1 = it.next();

    it.remove();//  ww w .j  ava  2 s .  c  o  m

    assertTrue("iterator should have next after first removal", it.hasNext());
    Object keyFromMap2 = it.next();

    it.remove();
    assertFalse(it.hasNext());

    // since iteration order is not defined for HashMap we need to make this test work with
    // both outcomes of the iteration
    if ((firstKey == keyFromMap1 && secondKey == keyFromMap2)
            || (firstKey == keyFromMap2 && secondKey == keyFromMap1)) {
        return;
    }
    fail("Wrong keys returned in iteration");
}

From source file:org.crazydog.util.spring.ObjectUtils.java

/**
 * Return as hash code for the given object; typically the value of
 * {@code Object#hashCode()}}. If the object is an array,
 * this method will delegate to any of the {@code nullSafeHashCode}
 * methods for arrays in this class. If the object is {@code null},
 * this method returns 0.//  w ww  .  j  a  va 2s  . com
 * @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 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:biz.wolschon.fileformats.gnucash.baseclasses.SimpleAccount.java

/**
 * This is an extension to ${@link #compareNamesTo(Object)}
 * that makes shure that NEVER 2 accounts with different
 * IDs compare to 0./*www  . j a  va 2  s. c  om*/
 *
 * Compares our name to o.toString() .<br/>
 * If both starts with some digits the resulting
 * ${@link java.lang.Integer} are compared.<br/>
 * If one starts with a number and the other does not,
 * the one starting with a number is "bigger"<br/>
 * else and if both integers are equals a normals comparison of the
 * ${@link java.lang.String} is done.     *
 * @param   o the Object to be compared.
 * @return  a negative integer, zero, or a positive integer as this object
 *      is less than, equal to, or greater than the specified object.
 *
 * @throws ClassCastException if the specified object's type prevents it
 *         from being compared to this Object.
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(final Object o) {

    int i = compareNamesTo(o);
    if (i != 0) {
        return i;
    }

    if (o instanceof GnucashAccount) {
        GnucashAccount other = (GnucashAccount) o;
        i = other.getId().compareTo(getId());
        if (i != 0) {
            return i;
        }
    }

    return ("" + hashCode()).compareTo("" + o.hashCode());

}

From source file:org.apache.hadoop.hbase.regionserver.LruHashMap.java

/**
 * Gets the hash code for the specified key.
 * This implementation uses the additional hashing routine
 * from JDK 1.4.// w ww.  ja va2s  . com
 *
 * @param key the key to get a hash value for
 * @return the hash value
 */
private int hash(Object key) {
    int h = key.hashCode();
    h += ~(h << 9);
    h ^= (h >>> 14);
    h += (h << 4);
    h ^= (h >>> 10);
    return h;
}

From source file:org.apache.camel.util.ObjectHelper.java

/**
 * A helper method for performing an ordered comparison on the objects
 * handling nulls and objects which do not handle sorting gracefully
 *
 * @param a  the first object//from   ww  w . j  a v a2s  . c o  m
 * @param b  the second object
 * @param ignoreCase  ignore case for string comparison
 */
@SuppressWarnings("unchecked")
public static int compare(Object a, Object b, boolean ignoreCase) {
    if (a == b) {
        return 0;
    }
    if (a == null) {
        return -1;
    }
    if (b == null) {
        return 1;
    }
    if (a instanceof Ordered && b instanceof Ordered) {
        return ((Ordered) a).getOrder() - ((Ordered) b).getOrder();
    }
    if (ignoreCase && a instanceof String && b instanceof String) {
        return ((String) a).compareToIgnoreCase((String) b);
    }
    if (a instanceof Comparable) {
        Comparable comparable = (Comparable) a;
        return comparable.compareTo(b);
    }
    int answer = a.getClass().getName().compareTo(b.getClass().getName());
    if (answer == 0) {
        answer = a.hashCode() - b.hashCode();
    }
    return answer;
}

From source file:org.executequery.gui.resultset.ResultSetTableModel.java

private void asStringOrObject(RecordDataItem value, ResultSet resultSet, int column) throws SQLException {

    // often getString returns a more useful representation
    // return using getString where object.toString is the default impl 

    Object valueAsObject = resultSet.getObject(column);
    String valueAsString = resultSet.getString(column);

    if (valueAsObject != null) {

        String valueAsObjectToString = valueAsObject.toString();
        String toString = valueAsObject.getClass().getName() + "@"
                + Integer.toHexString(valueAsObject.hashCode());
        if (!StringUtils.equals(valueAsObjectToString, toString)) {

            valueAsString = valueAsObjectToString;
        }//from w  w w . j  av  a 2s .com
    }

    value.setValue(valueAsString);
}