FAQ Database Discussion Community


Hashcode for string in different machine returns same value

java,hashcode
I have read that hashcode in a JVM instance returns same value. But in another JVM instance, the same value may not be returned. I tried the following program: public class demo { public static void main(String[] args) { String s = new String("Hello"); System.out.println(s.hashCode()); } } This program returns...

Is `hash` on a number consistent within a single ruby process?

ruby,hash,hashcode
When you run hash on a number, will it always return the same value within the same ruby process? It seems that 2.hash always returns the same value within a single process of irb, but if you close and reopen irb, you get a different value. Will it always stay...

when to implement comparable and when to implement equals in Java

java,equals,hashcode,comparable
In Java, when should I implement Comparable<Something> versus implementing the equals method? I understand every time I implement equals I also have to implement hash code. EDIT Based on answers I am getting below: Is it safe to say that if I implement Comparable then I don't need to implement...

Is it possible more than one elemets has same hashcode? [duplicate]

java,hashcode
This question already has an answer here: How do HashTables deal with collisions? 8 answers I have read in a book that "The value received from hashcode() is used as bucket number for storing elements." My doubt is if the bucket contains more than one elements(with same hashcode value),How...

Duplicate values in a hashSet

java,equals,hashcode,hashset
I am trying to count the number of combinations of 1, 5, 10 and 25 that sum to n. Given that I don't want any repetitions (like 1+5 = 6 and 5+1 = 6). I am using a hashSet. I implemented a class named ResultSet that saves the number of...

Java hashCode, artificial fields?

java,field,hashcode
Imagine the following problem: // Class PhoneNumber implements hashCode() and equals() PhoneNumber obj = new PhoneNumber("mgm", "089/358680"); System.out.println("Hashcode: " + obj.hashCode()); //prints "1476725853" // Add PhoneNumber object to HashSet Set<PhoneNumber> set = new HashSet(); set.add(obj); // Modify object after it has been inserted obj.setNumber("089/358680-0"); // Modification causes a different hash...

Why does this code not produce a correct hash?

c,linux,encryption,hash,hashcode
I had to write a tiny decryption program in C to brute force a key from one file, here "resource.bin", and use that one to decrypt another file using DES-EDE, here "rom_dump.bin". The indication for the correct key is that the decrypted file content starts with a ten digit number...

why don't List.GetHashCode and ObservableCollection.GetHashCode evaluate their items?

c#,hashcode
I think it is strange that the GetHashCode function of these collections don't base their hashcode on the items in their lists. I need this to work in order to provide dirty checking (you have unsaved data). I've written a wrapping class that overrides the GetHashCode method but I find...

How hashset checks for duplicate elements?

java,equals,hashcode,hashset
Kindly look into my code : HashSet<A> set = new HashSet<A>(); for (int i = 0; i < 10; i++) set.add(new A()); System.out.println(set.contains(new A())); Class A is defined as : class A { public boolean equals(Object o) { return true; } public int hashCode() { return (int) (Math.random()%100); } }...

Why hash function has done XOR on hascode?

java,hash,hashmap,hashcode
I read the explanation but I could not understand what we are achieving by doing XOR on the hashCode. Can anyone give some example. static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } This code was...

Hash function with ability to define its output generation length

matlab,hash,md5,hashcode,sha
I need to have a hash function in matlab which has capability to define its generated hashing length. For example, MD5 can generated hashing with length of 128 bits. However, I need to define various hashing function with designed lengths such as 10,16,20, ...

How to use Java 7+ Objects.hash with arrays?

java,arrays,java-7,hashcode
I really like Java 7+ style of writing hashCode() method: @Override public int hashCode() { Objects.hash(field1, field2); } It doesn't work correctly with arrays though. The following code: @Override public int hashCode() { Objects.hash(field1, field2, array1, array2); } will not work, as for array1 and array2 regular hashCode() instead of...

How does a hashSet admit elements

java,equals,hashcode,hashset
I have a list of objects that I need to add to a HashSet, say List<Node> books. Say further that no two books are equal in the very sense that their equals method would each return false; say, however, that their hashCode method each return 1. I am using this...

How can I overload equal method to make different objects have same hashcode value in unordered_multimap in my case

c++,hashcode,multimap
I have written a map like this: unordered_multimap<Point, int, StrHash, StrCompare> map StrHash() is to create hashcode and StrCompare() is to solve the hashcode collision. but I want to do something as follow: A and B have different hashcode value,but A equal to B, then run the StrCompare() method. how...

Implementing equals and hashcode for a BST

java,equals,hashcode
This question is sort of a follow up to Implementing hashCode for a BST. My question was poorly thought through and so I got an answer that I am not sure how to use. I need to implement equals for a BST: so that iff two BSTs are equal in...

How to write a by-the-book equals() method, possibly with hashCode()? [duplicate]

java,oop,netbeans,equals,hashcode
This question already has an answer here: What issues should be considered when overriding equals and hashCode in Java? 12 answers How would you write an equals() method? I need to be able to write a useable one for comparing playing cards in the program. I am using NetBeans...

Hash an integer by another integer [closed]

ruby,hash,hashcode
I'd like a way to hash an integer using another integer. It should produce a new hashed integer. It should accept an integer input and a key, the input is then hashed by the key and produced as an integer. The method would look like hash_method(input, key). Collisions won't matter...

java hashcode and equals [duplicate]

java,hashcode
This question already has an answer here: What issues should be considered when overriding equals and hashCode in Java? 12 answers Create the hashCode and equals method for the following class. private static class MyOb { private String name; private Integer quality; private final int MAXIMUM = 23; }...

HashCode calculation from double

java,double,override,long-integer,hashcode
In Effective Java there is an example of Complex class. That class has overridden hashCode which uses hashDouble method I have a question about. private int hashDouble(double val) { long longBits = Double.doubleToLongBits(re); return (int) (longBits ^ (longBits >>> 32)); } For what purpose it does (int) (longBits ^ (longBits...

Java equals() and hashCode() changes

java,object,equals,hashcode
What problems can arise if the result of the equals() and hashCode() methods changes across the lifetime of an object? Thank you!...

How are Strings created and stored in Java?

java,string,memory-management,immutability,hashcode
To understand how String objects are created and stored, I tried the following program and I see output against which I have query. Can somebody please help? package corejava.immutable; public class StringTester { public static void main(String[] args) { // TODO Auto-generated method stub String s1 = "Omkar Patkar"; String...

Maintaining hashCode contract for the specific condition, equals() depending on two integers

java,equals,hashcode
I have a basic class with the structure: class Employee { int eId; String eName; Employee(int id, String name) { this.eId= id; this.eName= name; } The conditions for equality is such that equals() should return true if any of the following is true: eId are same. eName are same. Lengths...

Number of calls of hashCode() and equals() in case of HashSet.contains() if hashcode returns a constant value

java,hashcode
I have read through Java docs pages, but I am not able to explain, why number of calls of hashCode() and equals() is varying like this? import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class NumberOfCalls { int field; public int getField() { return field; } public NumberOfCalls(int field) { this.field...

Java: Map with doubleKey type, how to make the right hashCode()?

java,dictionary,equals,hashcode,multikey
I have a MultiKey object as keys for a Map. A Key consists of a Name (String) and an ID (int). The following contract has to be fullfilled: Keys have to be equal if either the names of both keys are equal or the ids of both keys. How do...

Overriding equals and hashCode on a POJO with a List object

java,apache,equals,hashcode
I have a 2 POJOs that look like this public class Element{ private String name; private int number; //GETTERS AND SETTERS } public class Container{ private String subject; private String email; private List<Element> elements; //GETTERS AND SETTERS } And I need to verify if two Container objects are the same....

Why Objects.hash() returns different values for the same input?

java,hashcode
I ran the follow script(java), and it gave me the weird result. Does anyone can help to explain? import java.util.Objects; import org.apache.log4j.Logger; public class CacheTester { private static final Logger log = Logger.getLogger(CacheTester.class); @Test public void hashCodeTest() { for (int i = 0; i < 50; i++) { // if...

Comparing key elements of a Map using their hash codes [closed]

java,hashmap,hashcode
I want to compare the elements of a map using HashCode. Is it possible to do so? For example, my HashMap looks like this: HashMap<Integer,String> map=new HashMap<Integer, String>(); map.put(123,"ABC"); map.put(345,"Abc"); map.put(245,"abc"); I assume that all the values must have same hash codes, so that I can compare them and get...

How to override hashcode and equals method to avoid adding duplicate strings in HashSet in java?

java,equals,hashcode,hashset,java-collections-api
In my code I have a set of PlacesInfo object ie., Set<PlacesInfo> placeId; In this set I am adding placeId (String). I need to avoid adding duplicates to my HashSet. Here is my override method below. but, still it is adding duplicate elements to my set. So, how to avoid...

Can't output Guid Hashcode

sql,vb.net,guid,hashcode
I'm trying to use the hashcode of a guid as a random voucher name for a website, and have been trying to write new records to a SQL table with the Hashcode variable but it doesn't work. command.Parameters.Add("@voucherName", SqlDbType.NVarChar) command.Parameters("@voucherName").Value = Guid.NewGuid().GetHashCode() When using that code it just puts a...

String and Hashcode need explanation

string,hashcode
I have a problem here. I'm supposed to explain why my String "ab" returns 3105 when i use hashCode() on it. My main problem is that i don,t understand which value i.e s[0] has. s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] Can someone explain it? Thanks....

Java - new hashCode method

java,hashcode
I should override with several changes the method hashCode() for a array with length 500. Each array index (for example array[499]) must contains exactly 35512 object. I work with String of length 6 like that : "character character character number number number" (e.g "ABX015"). I must write a method hasdcode...

Algorithm used for bucket lookup for hashcodes [duplicate]

java,algorithm,hashcode
This question already has an answer here: What hashing function does Java use to implement Hashtable class? 5 answers In most cases, HashSet has lookup complexity O(1). I understand that this is because objects are kept in buckets corresponding to hashcodes of the object. When lookup is done, it...

Overriding hashCode when using HashMap, HashSet etc?

java,hashcode
The question is in the title. I use HashMap as follows: Map<Player, Partner> m = new HashMap<Player, Partner>(); //do some on m Where both Player and Partner are just a POJO representing data-model. public class Player{ private int id; private String name; //etc, GET, SET } public class Partner{ private...

Custom Dictionary TryGetValue doesn't find keys

c#,dictionary,enums,hashcode
I'm trying to create a base class that works like a state machine and that can accept any type of enum: public class BaseFSM <T> where T : struct, IConvertible { //Basic class that denote the transition between one state and another public class StateTransition { public T currentState {...

F# HashCode to enum conversion

error-handling,enums,f#,hashcode,bitmask
I have an enum of bit-masked error codes with a string representation and an binary int representation: type ErrorCodes = | NoError = 0 | InvalidInputError = 1 | AuthenticationFailedError = 2 | InvalidArgumentError = 4 | ItemNotFoundError = 8 | UnknownError = 16 As I run through the program,...

equals() without hashCode()

java,hash,hashcode
Can I only implement equals() but not hashCode() if I only need to compare objects and not yet plan to put the objects into any hash based containers? Seems all Java bibles say these two MUST be implemented together. :( My concerns: -If I always implement hashCode() together with equals()...

How to generate a hashcode from object with two list containing the same type of objects

java,list,hashcode
Let's say I have a class (the equal method also exists): public class SomeClassA { private int a; private int b; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return...

A way to store keys in a dictionary without storing the key?

c#,algorithm,dictionary,hash,hashcode
For example, if writing a dictionary class, collisions are rare, but they do exist. As a result, you need to store the key to make sure that when you find your key in the hashtable, it is the right one and not a collision. Sometimes the keys are long and...

hashcode implementation on boolean fields

java,hashcode
How do I implement a good hashcode if there are two boolean fields? Usually people just add the integer values to their hashcode values. But if I simply add 1 or 0 to my hashcode, I do not think it is good. Because if I have two objects of class...

How can I use a custom hash function in a HashSet or HashMap?

rust,hashcode
Since SipHasher is too slow for my use case, I'm trying to implement a custom hash function. I found an example which I used as base to get everything compiling. My current code looks like this: use std::collections::hash_state::{DefaultState}; use std::collections::{HashMap, HashSet}; use std::default::Default; use std::hash::{Hash, Hasher, SipHasher}; use std::marker; pub...